Administrator
E-mail: This e-mail address is being protected from spambots. You need JavaScript enabled to view it
Setting up a Successful Website
1. Choose a Niche - Today, anyone can have a website and sell merchandise or services on the internet. The choices are endless and only limited by your imagination. If you are already in a business and don’t currently have a website, then it’s simply a matter of deciding what name to chose. If you are thinking about setting up your first website and aren’t sure what niche to chose, you might consider a favorite hobby. I’ve always liked to collect & repair antique radios, so I setup a website called http://RadioExchange.net
The fastest way to achieve success and a high ranking on the internet is to build a website around a theme and niche which does not have a large amount of competition. For instance, if you were to start a web hosting website, it would be an uphill battle because there are thousands and thousands of hosting websites already on the internet fighting to get in the top 10 or 20 listings in the major search engines like Yahoo, MSN and Google. The more competition, the more costly and time consuming it is to get your website seen. An alternative is to research untapped markets or there’s a detailed report you can download on 109 Untapped Markets. The price is only $33. and it’s well worth it. To get your report go to Niche Topics http://7ac1x2.5millbucks.hop.clickbank.net
2. Purchase a Domain Name – Think of a domain name which uses the words which describes your business or what you will be selling. If your domain name contains the keywords which describe your business, you are likely to rank higher than with names which do not. For instance, if you are a realtor located in Orlando Florida it would be a good idea to register the domain name OrlandoFloridaRealEstate.com/net or org or Orlando-Florida-Real-Estate.com/net or org. A scientific way to determine the best name to use is to run keyword popularity searches using Overture's Keyword Tool at http://inventory.overture.com/
You can search for domain names and register them at http://fasthosting.com.au and they offer excellent 24/7 live customer service.
3. Set Up Web Hosting - Webster Hosting is what connects your Webster to the internet so it can be viewed by people around the world. Prices for hosting service range from free (I would not recommended a free service - you get what you pay for) to $39.95 per month which is on the high end. Some hosting companies charge a setup fee and demand a year commitment. I would not use any hosting service which charges a setup fee or expect a long term commitment because there’s so many which does not. http://Website-Supermarket.com offers excellent hosting services for only $7.95 per month with 24/7 live customer service and no set up fee and no annual commitment is required.
4. Design Your Website - If you have no experience or limited experience designing a website you can choose from thousands of professionally designed website templates for as low as $20. At http://fasthosting.com.au and they are available. Just browse through until you find a template you like, then click “Buy this Template” and download to your computer. They also offer 1000’s of clip art and photo art work ideal for customizing a website. Unlike many of the other template websites, after you’ve selected the site you want, if you need help customizing your template and getting on the Internet, they offer a set up service to get you up and running quickly. If you choose to customize the template yourself you will need web design software such as Macromedia Dreamweaver or Front Page and Image software such as Adobe Photoshop. Macromedia Fireworks is also a super software program for designing websites.
5. Upload Your Web Site files to your Hosting Service’s Server – Most Web creator software such as Front Page and Macromedia Dreamweaver has built in FTP (File Transfer Protocal) capability. A super program I recommend for uploading and downloading files is Cute FTP by GlobalScape. You can download a copy from their website at http://Cuteftp.com
6. Submit Your Website to the Search Engines - I recommend Submit-It which is a Free service that Submits your URL to all of the major Search Engines such as Yahoo, MSN & Google. Their website address is http://www.submitplus.com/scripts/affiliates/clickthru.cgi?id=bj7780
http://fasthosting.com.au has reference material and articles to help you make your Website a Success!
Optimising for your website for Google
Search engine optimization is the process of choosing targeted keyword phrases related to a website, and ensuring that the website places well when those keyword phrases are part of a Web search.
ON-PAGE OPTIMIZATION FACTORS:
The Major Factors Are:
Meta Tags, Header Tags, Text-body tag and Alt image tags:
1- META TAGS:
Meta Tags are code in your HTML that is invisible to the visitors of your web site but are read by some web spiders and search engines.
Meta tags used by a large percentage of the top search engines as one of the main guidelines on how they will index your site
The Main Meta Tags are:
• Title Tag
• Description Tag
• Keyword Tag
Targeting the right keywords:
Do keyword research- it is very important in building traffic
To do your keyword research visit this website <a href='http://fasthosting.com.au'>http://fasthosting.com.au</a>
Select a short list of 3 to 4 keywords
Title tag:
The page title should include ONLY your main keywords. The least amount of words you can place in the title, the more weight Google will give to each of the keywords and the higher you will rank.
The title is the most important piece of information search engines use to index Web pages. Include the title of your page and 3-5 important keywords. Format your site title as follows:
Site title, keyword1, keyword2, keyword3
You may use your URL, or the name of your company as your site title.
• Make sure it specifically describes your product or service,
• Makes proper use of 3 or 4 keywords,
• Use between 10 and 80 characters long.
Tips:
• Taken out all of the "ands"
• Replaced one of the "ands" with a "|" character
• Always Combine Your Keywords In The Page Title
Description Tag:
The Meta description tag describes your site's content, giving search engines' spiders an accurate summary filled with multiple keywords.
• Use a descriptive paragraph or sentence that is relevant to your page.
• If possible, use a sentence or paragraph that is present in the content of your page
• Use up to 500 characters, including spaces.
Keyword Tag:
Use a list of keywords that are relevant to the content of your web page. Use your url as the first key word and separate the keywords with commas. Format the key words as follows:
www.sketch-plus.com, keyword1, keyword2, keyword3, …..
Add 5-10 Keywords
• For best results a tag sized between 50 and 250 characters.
• Note that keywords should be separated with commas.
Free Meta Tag Analyzer:
This Meta tag analysis tool will help you analyze your web pages and
check for search engine compatibility.
http://www.hypergurl.com/form.html
More Sites for SEO:
http://www.submitnet.net/
<a href='http://fasthosting.com.au'>http://fasthosting.com.au</a>
2- HEADER TAGS:
Headers are used to break entries up into logical sections.
Add h1 header tags- (Place your most important keyword) it's best to place your h1 header tag on the top left hand or top/middle portion of your page.
When Google reads a webpage, it views the text from the top left hand side of the page to the bottom right hand side of the page.
Add h2 header tags- (Place your 2nd most important keyword) should be placed somewhere towards the top half of your webpage.
3- TEXT- BODY TAG:
The body element defines the documents' body. It contains all the contents of the document (like text, images, colors, graphics, etc.).
• When writing the content, try to evenly sprinkle your main keywords throughout the copy. Don't overdo it though.
• Try to mention each keyword in a natural way as you are writing
• Include at least one of the keywords per 1-2 paragraphs, depending on how large your page is.
• Make sure to mention your main keyword at the very top left and the very bottom right hand side of the webpage
• Bolding, italicizing and underlining...Once we've finished writing the copy, we should go through and bold, italicize, or underline some of the keywords only 1 time each, maximum.
• Any keyword must be used 4 times or more in your site's HTML body. This is highly recommended for best ranking results.
• Avoid Excessive Keywords- No word to be used more than 30 times throughout the page.
4- ALT IMAGE TAGS:
ALT tags are images' descriptions.
• Place your keyword 1 in the alt image tag of the very top image in your webpage.
• Place your other 2 keywords plus an extra word like "picture" or "image in the alt image tag of 2 more graphics throughout your webpage.
LOAD TIME ANALYSIS:
If your Web site does not load in 12 seconds or less with a 56k connection, statistics show that about 45% of visitors will leave the site.
• Optimized you site for 56k modem users- Load time 12 second or less.
• Try to keep your homepage under 50k and your other pages under 40k.
SEARCH ENGINE GUIDELINES:
Always remember this general rule when building your site: “Search engines do not like to be fooled”. Do not try to manipulate your listings through sneaky methods. Provide useful, relevant content, and you will never have to worry about search engine guideline violations.
• Hidden Text - you never hide text.
• Excessive Keywords-Use keywords naturally in sentences and paragraphs.
• No word to be used more than 30 times throughout the page.
• Repeated Keywords- No keywords to be repeated multiple times in a row. We recommend using keywords naturally in sentences and paragraphs.
• Doorway Pages- Doorway pages are discouraged by most search engines.
• Harmful Redirects- Redirecting pages have a hard time being indexed by search engines.
• Frame Issues- It is recommended for sites that use frames to implement a descriptive NOFRAMES tag with relevant text content.
• Macromedia Flash Issues- Don't create all-Flash pages for any content you want to get indexed - instead, put that content in the HTML portion of the page.
How to build an E-Commerce site yourself
To build an ecommerce web site yourself is really not such a difficult task when using the right kind of tools. You will want to build an ecommerce website using the latest technologies such as a user-friendly shopping cart, integrations with top auction sites as well as a payment gateway. Although the web site design is important, correct usage of the ecommerce marketing tools will result in many business transactions.
Here are some points to consider when getting down to building an ecommerce website.
a) Its design should facilitate easy buying of goods and services
b) Your products or services should be of value to the customers
c) Offer personal attention to all customers
d) Offer discounts and e-mail promotions to them so that they keep returning to your site
The design of your web site should mirror your business and what you want to market. The website is your interface with your customers and through it you must be able to convince them to buy your product. At the same time it should not be aggressive towards sales and scare off the visitors.
When you build an ecommerce website you need to use as many keywords (the words through which the search engines bring visitors to your online store) as possible to ensure that the search engines list your store higher when the visitors are looking for the items you sell.
With more than hundred different internet browsers currently available you need to ensure that your site is compatible to be picked up by all of them. Build an ecommerce website that is viewed in at least Internet Explorer 4.0+ and Netscape 4.0+. This is helpful in getting traffic to your site.
The images used on your site should detail your merchandise clearly. Also be sure to optimize your images for fast download; one loses a lot of customers who can’t wait endlessly for the pictures to show up.
Site navigation should be easy to understand and use. Answer any and all questions you think visitors may have in the FAQ section. Buyers hate to meander on a site if it leads nowhere, so the easier your site navigation the more sales you will have. Build an ecommerce website specially designed for your business in a cost effective way to promote your products or services.
Every business needs a website
There are many sites on the internet (about 50 million active sites and over 100 million active Hostnames). However, many of these sites don’t serve their intended purpose, or in other words, haven’t reached their full potential.
For a business that isn’t an internet based business that could still survive without the internet or computers, what is the purpose of a website you may ask? Other than selling something online, there are still a number of good reasons for having a website: To alleviate menial tasks, to market yourself inexpensively or merely to provide basic and freely available information about your business.
There are really two types of websites, either selling something online or providing online information. These two categories can be expanded to a great extent, covering types of online products or services and various categories of information, e.g. brochure ware type information, blogs, forums, educational, etc. But for the purpose of this article I have contained it to just the two – therefore, as a visitor to a website, you either pay money for something or you get information that is publicly available.
I will be focusing on the second type of website, i.e. where someone has information that they want to share.
The first reason to have an informative type website that I’m going to discuss would be to alleviate menial tasks. Most businesses have many repetitive tasks that need to be performed on a daily basis. If you can highlight these tasks and categorise them and separate out the tasks that involve client interaction, you then have valuable information that can be incorporated into your site. A very basic example would be if you have a form that each of your clients need to fill out (for an application, registering details or whatever), you could make that form available on your website and direct your clients there. This will free up a staff members’ time that is required to explain the procedure over and over, it will also save on postage costs, paperwork, paper or the actual time spent emailing the form to your clients. This in turn would also save time spent on processing the information on the completed forms; it will already be in soft copy in the correct format that you chose on your website. Your imagination is the only boundary of what can be achieved on your website and to what level you want to take it to...
The next reason to having a website would be to market your business. If you’re in business, it means that you want people to know you exist, and with the internet at our disposal, why not use it? In my article “As a Small Business Owner, Why Do You Need Your Own Domain Name?” I explained the benefits of owning your own domain name. If you have registered your domain already, then you may as well publish a website and get some marketing out of it. Again, it is entirely up to you how successful you want to make it. There are many guidelines on the internet explaining how to improve your website’s exposure and attract more traffic/potential clients to your site.
Finally, if neither of the two reasons for having a website have grabbed your attention, then you should still do it anyway; even if it’s just to advertise your contact details. In the past, people would solely use directory listings to find business details, however these days, the internet has made searching for businesses, including your competition, very easy and widely used. Therefore it’s a good idea to have your contact details on a simple site. Even a copy of your business card published as a one page site is better than nothing.
Next time you’re looking for information from a specific business, see if the information you are looking for is or could be found on their website and explore the possibilities.
<a href='http://fasthosting.com.au'>Fast Hosting</a> has been involved in the Hosting industry for over 6 years working with global companies.
Choosing a Domain
Your domain name choice can be critical to your business yet many do not know how to choose a domain name. If you want a successful business you will need it to be accessible from the internet. To achieve that you will need a website, and hence a domain name. The domain name is the name by which your site is known, such as mysite.com and the number of domains registered on the internet has increased from about 10 million in the year 2000 to over 50 million now.
There are a few approaches that can be taken to choosing a domain name, and each can be appropriate according to the circumstances. It is not always a good thing to name your website after your product, especially if you are trying to get it established in the market place. For example, if you invented an ionic hydrogenator that no one had ever heard of, the domain ionichydrogenators.com would not be one that many people would search for, and neither would the keyword ionic hydrogenator.
It is important that the name you give to your website will have the possibility of being found by somebody searching for an answer to their problem on the internet. If your ionic hydrogenator made your car go faster, then fastcars.com or fastengines.com would be more likely to attract traffic.
If you already have an offline business that you want to put online, you will need a domain name that is either the same as that of your business, or that describes what it does. For instance, if your business is “Resume Writers” then your domain name should be resumewriters.com. If you find that is taken, do not opt instead for writeresumes.com since nobody will find you. Far better would be resumewriting.com or resumewriter.com.
For tips on choosing the right domain email href=' This e-mail address is being protected from spambots. You need JavaScript enabled to view it '> This e-mail address is being protected from spambots. You need JavaScript enabled to view it >.
Agile - Using Hibernate
An Overview of Object-Relational Mapping (ORM)
It is no secret that relational databases are the most common type of databases in a majority of organizations today when compared to other formats (for example, object-oriented, hierarchical, network). Product names such as Oracle,
Microsoft SQL Server, MySQL, IBM DB2, and Sybase are common terms used by developers in our line of work.
On the computer languages side of things, object-oriented (OO) programming has become the norm. Languages such as Java, C#, C++, and even OO scripting languages are common discussion topics among developers.
(because of the use of embedded SQL or stored procedure calls) to heavy-handed technology, such as EJB's entity beans.
nd secure execution of EJB's entity beans (which also map object attributes to relational database fields).
of this class throughout your applications as POJOs. For example, you can use a save method for a given object and the underlying ORM framework will persist the data for you instead of you having to write tedious INSERT or UPDATE statements using JDBC, for example.
chapter under "Recommended Resources."
Hibernate also supports the EJB 3.0 standard, so should you need to move to EJB 3.0, it'll be an easy transition (in fact, EJB 3.0 is based on many of the concepts and techniques found in Hibernate). EJB 3.0, as you might already know, aims to simplify working with EJB technology prior to this release; for example, EJB 3.0 provides a lighter-weight persistent API similar to the one provided by Hibernate.
However, if you do not need the many services provided by EJB technology, you can use the Hibernate core technology by itself (without needing a big EJB container product such as an application server).
Database relationships are typically defined in terms of direction and cardinality (multiplicity in OO terminology). From an OO perspective, relationships are defined as association, inheritance, or aggregation. Many software development projects use ORM either with existing databases or are required to conform to standards established by a database group within the organization; hence, I will approach our relations discussion from a database perspective.
Note
Cardinality can be defined as one-to-one, one-to-many (or many-to-one depending on which direction you look at the relationship), and many-to-many. We look at each briefly:
- A one-to-one relationship is when a record in table 1 can have exactly one associated record in table 2. For example, a record in a Person table might have exactly one related record in a JobTitle table.
- A one-to-many relationship is typically seen in parent-child relationships where a parent record can have several related records in a child table (for example, related via the parent's primary key).
- A many-to-many relationship is where a record in table 1 can have several related records in table 2 and vice versa. For example, an Employee table might have more than one record in a Project table (because an employee can be involved in multiple projects). On the flip side, a record in the Project table might have several related records in the Employee table because a project can have multiple employees assigned to it. Also, this type of relationship is typically achieved by using an (extra) association table (for example, a ProjectEmployee table that contains foreign keys pointing to the two main tables).
Object Identity
Cascade
Mapping
There are various mapping strategies we can employ, such as horizontal mapping, vertical mapping, and union mapping. In vertical mapping, each class in a hierarchy (abstract or concrete) is mapped to a different table. For example, if we have concrete classes named Dog and Cat, both inheriting from an abstract class named Animal, we would end up having three tables in the databaseone for each class. In horizontal mapping, each concrete class is mapped to a table. In union mapping, many classes (presumably part of the same hierarchy) map to a single table.
Although vertical mapping is more flexible, it is also more complex because it requires multiple tables to extract all the data. Hence, we will use horizontal mapping because it is a simpler design and can provide faster performance, especially for simple to reasonably complex applications. To be more specific, our approach will involve one table per class mapping strategy.
In-Memory Versus Persisted Objects
Another way to look at this distinction is that if we remove an object from memory (for example, by removing it from a Java collection), it does not necessarily mean the record has been physically deleted from the database (unless, of course, we mapped the collection in Hibernate to have automatic cascading during parent deletes).
Design our Sample Database
Now that we have covered some OR concepts, it is time to set up our database so that we can move one step closer to building an application's user interface with the help of the Spring Web MVC Framework.
"XP and AMDD-Based Architecture and Design Modeling," shown in Figure 5.1.
Given the simplicity of our sample application, Time Expression, and its domain model, we could create a physical database model (PDM), also known as an Entity-Relationship (ER) diagram, which contains entities identical to ones in our domain model, with the addition of columns and data types and other database constraints. However, let's denormalize it just a bit for performance and ease of development purposes.
Figure 5.2 shows a PDM, denormalized a bit from our Domain Model and with data types (for example, varchar) added to it. The denormalization is related only to the Timesheet and Time tables.
You will notice we are using Java-like naming conventions for the table and column names. This makes our job easier because we can use the same names across all artifacts related to Time Expression while also gaining consistency across them. In other words, we have matching names from User Story tag/name to controller classes to model (domain) objects to the Hibernate persistent bean Java code and finally, to the database tables and columns (shown in Figure 5.2).
This naming approach makes our job easier in two ways. First, we don't need to think about the naming convention for each layer, and second, it reduces the amount of mapping details we need to specify in our Hibernate class mapping files because we do not have to specify a corresponding column name for each property being mapped (as we will see later in this chapter).
Note that for database objects (such as tables and sequences), I tend to use names starting with an uppercase letter, whereas column names start with a lowercase letter.
The following are some disclaimers and/or explanations for the PDM we looked at in Figure 5.2.
By combining the Timesheet and Time entities into one physical table, there is the possibility of wasted database space by unused columns. For example, there is a good chance that MinutesSat and MinutesSun will be less frequently used (unless employees in this company work most or all weekends). However, the advantages of the simpler design and performance arguably outweigh the disadvantages of a bit of wasted space.
We have used Minutes
We have a Password column in the Employee table. Typically, in larger organizations, you might end up using something like a central Lightweight Directory Access Protocol (LDAP) authentication service. However, this works well for our small (and sample) application, Time Expression.
Now that we have a PDM (see Figure 5.2), we can move to the next level down, which is to write a DDL script that can be used to create the actual databse. Our DDL script is embedded inside one of our Ant scripts, named timexhsqldb.xml. The table names, column names, and data types in our DDL script closely match the PDM in Figure 5.2, as they should.
CREATE TABLE Timesheet
( timesheetId IDENTITY NOT NULL,
Second, we have seen some test data being inserted; this is for use by our JUnit test cases covered later in this chapter. For the sake of simplicity, I have not created any primary or foreign key constraints, as we typically should in a real-world application. Also, the focus of this chapter is to demonstrate features of Hibernate and not necessarily database design.
Where HSQLDB and Hibernate Fit into Our Architecture
HSQLDB
HSQLDB provides a good amount of ANSI-92 SQL-compliant features (and many enhancements from more recent SQL standards)more than we will need in this book. Furthermore, most of the features defined by JDBC 2, and some from JDBC 3, are also supported. HSQLDB's popularity has grown significantly since its inception a few years ago, and it is commonly found bundled with open source and commercial Java-related products such as JBoss, OpenOffice.org, Atlassian's JIRA, and many more.
At the time of this writing, the HSQLDB project was one of the top 50 ranking in more than 100,000 SourceForge.net projects.
HSQLDB can be found at http://hsqldb.org. There are ample setup instructions on this site to download, install, and configure it. I'm using version 1.8.x in this book.
Now we need to start the HSQLDB server and create the database using our DDL file. However, first, let's copy the hsqldb.jar file from the HSQLDB install directory to our lib/ directory; for example, on my Microsoft Windows XP-based system, I typed the following:
copy \hsqldb\lib\hsqldb.jar \anil\rapidjava\timex\lib\
C:\anil\rapidjava\timex).
Assuming our HSQLDB configuration is set up correctly, we can now type the ant -f timexhsqldb.xml starthsql command to start the HSQLDB server, as demonstrated here:
C:\anil\rapidjava\timex>ant -f timexhsqldb.xml starthsql
C:\anil\rapidjava\timex>ant -f timexhsqldb.xml execddl
The following properties are related to HSQLDB; that is, the hfile property points to a local set of files under the timex/data/ directory, the halias is the alias we will use in our client applications to connect to the HSQLDB server, and the hport is the port number the HSQLDB server will listen to:
classname="${hclass}" classpath="${hjar}" args="${hfile} -dbname.0 ${halias} -port ${hport}"/>
driver="org.hsqldb.jdbcDriver" url="jdbc:hsqldb:hsql://localhost:${hport}/${halias}" userid="sa" password="" print="yes">
HSQLDB is bundled with two tools you should read about in the HSQLDB documentation: HSQL Database Manager (GUI) and SqlTool (command-line based). These are nice tools for working with our database. Meanwhile, you will find two convenient ant tasks in our timexhsqldb.xml file, hsqldm and sqltool, which can be used to start these two tools. For example, to start HSQL Database Manager, type the following on the command line:
ant -f timexhsqldb.xml hsqldm
Be sure to read about the various modes HSQLDB can run in (such as local versus server and in-memory versus persistent); we will use the server and persistent mode. For example, we could also use the very same HSQLDB database files (found under our timex/data/ directory) as follows:
jdbc:hsqldb:file:${catalina.base}/webapps/timex/WEB-INF/data/timexdb
As an added benefit, HSQLDB has a small enough footprint to run entirely in memory. For example, we could deploy our sample application with HSQLDB, bundled in the same web archive (WAR) file, essentially making the WAR file a fully self-contained system with no need for an external database!
Working with Hibernate
Hibernate has recently gained a lot of momentum in the world of Java database application development. Although products such as Toplink and others have been around for many years, Hibernate is open source (hence, free), stable, mature, well documented, and relatively easy to learn; these are probably just a few reasons why it is as popular as it is. Hibernate has been around for several years but was recently acquired by the JBoss group. (However, it continues to operate autonomously as an open source project.)
The Hibernate persistence framework can make working with relational databases using Java a pleasant experience. This is especially true if you have been developing using JDBC or using heavy-handed type entity beans. Defining the mappings can seem like a slight pain initially, but as you will see in later in this book, there are tools to generate these mapping files.
The extra work of defining mappings is well worth it because our persistence code will be cleaner and we will have automatically eliminated the need for Data Access Objects (DAOs), which typically are objects that know how to persist themselves. We also won't need Data Transfer Objects (DTOs), which are objects used to encapsulate business data and get transferred between layers of an application.
As of the writing of this book, Hibernate supported the following databases (other databases are supported via community efforts):
One thing worth mentioning here is that members of the Hibernate/JBoss team are part of the EJB 3.0 expert group, a group that helped simplify the EJB specifications. It should come as no surprise, then, that the latest version of Hibernate supports the EJB 3.0 specification. However, we will not cover the EJB 3.0 here because it is outside the scope of this book. The focus of this book is on lighter-weight (and open source) frameworks, not heavy-handed specifications that require commercial application servers to use these features.
Before diving into Hibernate concepts and terminology, let's look at a simple hibernate program and the setup involved. The following sections outline the steps required to get our first test program, SimpleTest, working. But first, let's take another look at the development directory structure we established in Chapter 3.
Figure 5.4 shows the development directory structure for Time Expression. It is important to review this again because we will create several files in this chapter and refer to them using their relative path namesfor example, model/Department.java means file Department.java in the timex/src/java/com/visualpatterns/timex/model/ directory.
We will place the three types of Hibernate files (discussed next), a Hibernate configuration file, related Java classes, and table mapping files, in the same directory. This is the practice recommended in Hibernate documentation and examples.
The naming convention for the Hibernate mapping files is typically the name of the Java class name with a suffix of .hbm.xmlfor example, Timesheet.hbm.xml.
First we will create a file named hibernate.cfg.xml in the timex/src/java/com/visualpatterns/timex/model/ directory. This file will contain a SessionFactory definition (discussed later in this chapter) and reference to our first mapping file, Department.hbm.xml. Let's review some of the interesting lines from this file:
org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost:9005/timex
sa
We will create our first mapping file, Department.hbm.xml, in the timex/src/java/com/visualpatterns/timex/model/ directory.
To keep things simple, I chose to start with the Department table because it is one of the simpler tables, and we will also use it in our slightly more complex example later in this chapter. Let's review the Department.hbm.xml file a bit closer.
The following line maps our Java class to the database table:
We will write two Java classes, one called com.visualpatterns.timex.model. Department and another called com.visualpatterns.timex.test. HibernateTest.
The Department.java (under src/java/com/visualpatterns/timex/model) contains a simple JavaBean class, which provides accessors (get methods or getters) and mutators (set methods or setters) for these two variables:
String departmentCode; String name;
Now we will write some simple code to accomplish two things: test the Hibernate setup and also look at a basic example of how to use Hibernate. Let's review our HibernateTest.java file (under src/java/com/visualpatterns/timex/test) step-by-step.
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction(); Department department; department = (Department) session.get(Department.class, "IT"); System.out.println("Name for IT = " + department.getName());
List departmentList = session.createQuery("from Department").list();
for (int i = 0; i < departmentList.size(); i++) {
department = (Department) departmentList.get(i);
System.out.println("Row " + (i + 1) + "> " + department.getName()
+ " (" + department.getDepartmentCode() + ")"); }
sessionFactory.close();
Now we are going to try running our test using our Ant build.xml file, introduced in Chapter 4, "Environment Setup: JDK, Ant, and JUnit." Our Ant target, hibernatetest, is as follows:
classname="com.visualpatterns.timex.test. HibernateTest"/>
Notice that there are errors on the screen, such as package org.hibernate does not exist. This means it is time to download and set up Hibernate in our environment!
Hibernate can be found at http://hibernate.org. At this point, we will follow the setup instructions provided on this site to download and install it to the recommended (or default) directory.
After we have the Hibernate installed, we will copy all the recommended libraries (for example, hibernate3.jar and antlr.jar) in the Hibernate documentation to the rapidjava/lib directory.
Note that I also needed to copy ehcache-1.1.jar and antlr-2.7.6rc1.jar (which was not mentioned in the Hibernate reference documentation at the time of this writing). Here is what I ended up with, in my timex/lib/ directory:
Before rerunning our test, we need to temporarily alter the hibernate.cfg.xml file. Because we have only Department.hbm.xml implemented, we need to temporarily remove the following lines (to conduct this test) from our hibernate.cfg.xml file:
Now that we have looked at a small preview of Hibernate-related Java code and XML files, let's get a high-level understanding of some basic Hibernate concepts before we look at slightly more complex Hibernate code for the Time Expression application.
Hibernate provides dialect classes for the various supported databases mentioned earlier. This is essentially to ensure that the correct and most optimized SQL is used for the database product being used. For example, we are using the org.hibernate.dialect. HSQLDialect class for HSQLDB.
SessionFactory, as you might guess, manages a collection of Session objects. Each SessionFactory is mapped to a single database. The Session object essentially is a wrapper for a JDBC connection and is also a factory for Transaction objects. A Transaction is a wrapper for the underlying transaction, typically a JDBC transaction.
A side but important benefit of using Hibernate is that it provides built-in database connection poolinghence, one less thing for us to worry about. Connection pooling, as you might be aware, is used to create a specified pool of open database connections (see connection.pool_size property in our hibernate.cfg.xml). By using a pool of connections, we can achieve more efficiency in our use of the database because existing open connections are reused. Furthermore, we get performance gains because we reuse open connections, thereby avoiding any delays in opening and closing database connections.
Several methods available in Hibernate's org.hibernate. Session interface enable us to work with database records as objects. The most notable methods are save, load, get, update, merge, saveOrUpdate, delete, and createQuery (several of these are demonstrated later in this chapter).
Another noteworthy interface to mention is org.hibernate. Query, which is returned by calling the Session.createQuery Hibernate method in our HibernateTest.java file. The Query class can be used to obtain a group of records in the form of a java.util. Collection object (for example, Hibernate provides mapping elements such as an array, set, bag, and others).
One last interface worth mentioning here is org.hibernate. Criteria, which can be used for database queries in an OO fashion, as an alternative to the Query class (which is HQL based).
The following is a partial list of types supported: integer, long, short, float, double, character, byte, boolean, yes_no, true_false, string, date, time, timestamp, calendar, calendar_date, big_decimal, big_integer, locale, timezone, currency, class, binary, text, serializable, clob, and blob.
HQL is Hibernate's robust SQL-like query language, which is not case sensitive. HQL has many of the features defined in ANSI SQL and beyond, because it is fully object-oriented and supports OO concepts such as inheritance, polymorphism, and more. The following are some basic clauses and features supported in HQL. You wil
Sample Application - Environment Setup: JDK, Ant, and JUnit
Java Platform Standard Edition Development Kit (JDK)
Because we are doing Java development, it would make sense to have the necessary Java tools (for example, compiler) set up. If you do not already have the JDK installed on your machine, or if you have an older version than ones required by JUnit and Ant, you should get the latest version from the java.sun.com website and have it set up on your machine so that commands such as java are in your path.After downloading and installing Java, you should be able to type the command javaversion to test your setup and ensure you have the correct version of the JDK, as shown next:
C:\anil\rapidjava\timex>java -version
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
Directory Structure
Let's revisit the directory structure we covered in the previous chapter. Figure 4.1 shows the directory structure. It is important to see this again now before we jump into the Ant discussion. Let's review some of the more notable subdirectories here:
- src directory will contain all the Java, HTML/Javascript, XML, and all other input/source files that we will develop ourselves.
- build will contain the output of our builds (for example, compilation, copying of web and library files, and so on).
- lib will contain all external JAR files required to run our application.
- dist will contain our web archive (.war) file, which contains all the web-related files, compiled .class files, .jar library files, and more.
Ant
I would not be exaggerating by claiming that Ant (ant.apache.org) is perhaps the single most important and widely used tool in the world of Java today! Therefore, mastering this tool is the key to rapid Java development. So, it is no surprise that I'm covering this tool directly after the JDK section, because I consider Ant the most vital tool to install after you are done with the basic Java setup.
By now you probably realize the important role Ant plays in Java development. We will use Ant extensively in this book! For example, we will use it to build our application, deploy it, run various Java programs, create our database, run our tests, and more.
Ant was originally developed by James Duncan Davidson, from the Open Source Program Office at Sun Microsystems. Ant is a cross-platform build tool that eliminates a lot of complexities and quirks that can be found in tools such as Unix make. Instead of using shell commands proprietary to the operating system, Ant uses XML files to specify various tasks. Ant is a highly extensible tool, mainly because of the huge market of builtin and external (open source and commercial) tasks available for Ant, which makes it so powerful. In addition, you can easily write your own custom extensions.
Given that Ant itself is developed in Java, it is portable, and according to the Ant website, it has been tested on various Unix systems, Microsoft Windows, Mac OS X, and others. The ant.apache.org website provides ample (and up-to-date) information on how to get Ant set up on your system; if you do not already have Ant installed on your system, you should go ahead and do so at this point.
When you do have Ant set up successfully, you should be able to run the ant command without specifying the full path. That is, the ant command should be in your path because the remainder of our book will reference ant without the full path. For example, if you typed ant -version on the command line, you would see something similar to what is shown in Figure 4.2
JUnit
JUnit, originally written by Erich Gamma (Gang of Four, Design Patterns book) and Kent Beck (also author of Extreme Programming), is an open source Java testing framework commonly used for unit testing of Java code. It can be downloaded from the junit.org website; this website provides not only setup instructions, but also articles on unit testing and many benefits to writing tests first.
Test-driven development (TDD), a term coined by Kent Beck, can enable better code design, cleaner code (fewer print/debug statements and test scripts), and more efficient code. Because we will follow this approach by writing tests first in this book, it makes sense to cover JUnit directly after JDK and Ant sections.
JUnit Standalone Runners
For setting up JUnit, again I will refer you to the installation instructions found on the product's website, junit.org. The JUnit test runner (Java main class) comes in two flavors: a textual version and a graphical version. The graphical version is available in two variations, a Java Swing-based one (recommended) and an older, AWT-based one.
After you have JUnit set up correctly, you should be able to type the following command (from the JUnit install directory; for example, C:\junit3.8.1) and be able to run the Swing version of JUnit's user interface, shown in Figure 4.5:
java -cp junit.jar junit.swingui. TestRunner
JUnit in Eclipse SDK
In the next chapters, we will continue to use the standalone JUnit test runners for working with JUnit, described here. However, when I introduce Eclipse later in the book, we will switch to using JUnit within Eclipse (shown in Figure 4.6), which makes running and debugging JUnit tests much more convenient. However, there might be times when you want to run batch tests using the Ant junit task on a server or even test a single class outside of the IDE, using one of the JUnit built-in runners.
SimpleTest: Making the Tools Work Together
Assuming we have the JDK, Ant, and JUnit set up correctly, we should be able to now write a sample JUnit Test and try it out.
Regardless of which flavor of JUnit we use, we can either pass it our test class name or type it into the UI runner. For example, if we wanted to write a very simple test case to test the fact that 2 + 3 = 5, we would do the following:
· Develop a JUnit test classfor example, SimpleTest.java.
· Run the JUnit class using one of the JUnit runners.
SimpleTest.java
This book's code file (available on the book's website) shows the complete code for SimpleTest.java. The code should be fairly straightforward to follow. There are two test methods: testAddSuccess and testAddFail, as shown here:
public void testAddSuccess()
{
assertTrue(value1 + value2 == expectedResult);
}
public void testAddFail()
{
assertTrue(value1 - value2 == expectedResult);
}
The testAddSuccess method will be successful, whereas the testAddFail method will fail (because 2 minus 3 does not equal 5). The success or failure is determined by the JUnit assert methods, which throw an exception if the test failed.
JUnit Assert Methods
We saw an example of JUnit's assertTrue method in our example previously; JUnit also provides several other flavors of assert methods, as shown next:
· assertEquals
· assertFalse
· assertNotNull
· assertNotSame
· assertNull
· assertSame
· assertTrue
Running SimpleTest (a Single JUnit TestCase)
To try out the code we saw for SimpleTest, we need to create the SimpleTest.java file, compile it, and try running it. So, let's create the SimpleTest.java file under our src/java/com/visualpatterns/timex/test/ directory. Then we can simply type the ant command from the timex/ directory to compile our unit test source code.
Now, let's try running our SimpleTest test case (from the top-level timex/ directory) using the JUnit test runner, as demonstrated here:
C:\anil\rapidjava\timex>java
-cp \junit3.8.1\junit.jar;build/timex/WEB-INF/classes
junit.textui. TestRunner com.visualpatterns.timex.test. SimpleTest
We should see something similar to what is shown in Figure 4.7.
We could also run SimpleTest.class in the JUnit swing runner, as shown next (Figure 4.8 shows the result of this command):
java -cp \junit3.8.1\junit.jar;build/timex/WEB-INF/classes
junit.swingui. TestRunner
com.visualpatterns.timex.test. SimpleTest
The junit.framework. AssertionFailedError related messages you see in both the test runners is actually a good thing; these are valid JUnit errors because our testAddFail method failed.
Running JUnit Tests in a Batch
There is one more way we can run JUnitthat is, as an Ant task. Next we'll take a look at how we do that.
First, let's copy the junit.jar file from the JUnit install directory to the
Second, we need to copy the same junit.jar to our timex/lib directory; this also will assist with our builds using Ant.
Now let's revisit our build.xml file. This file contains a target named test, which uses the junit task, as shown in the following excerpt:
If we run the command ant test, the results of the batch test would appear in a file named TEST-com.visualpatterns.timex.test. SimpleTest.txt in the current directory, an excerpt of which is shown here:
Testsuite: com.visualpatterns.timex.test. SimpleTest
Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 0.021 sec
Testcase: testAddSuccess took 0.004 sec
Testcase: testAddFail took 0.003 sec
FAILED
That's pretty much all there is to JUnit! Although JUnit is a simple framework, it is powerful because you can have several test methods within each JUnit TestCase subclass (a suite). Furthermore, you can roll up the individual suites within other suites (with no limit). For example, you can create a class named AllTests, which calls the suites of all other Test classes in the test package.
Test-driven development (TDD) has brought the concept of test first design to the fore-front. This approach has several benefits and hence we will write tests first in this book, whenever possible.
Writing tests first takes a little bit of getting used to, and many times, you will wonder if you really have the time to write tests given the pressure of deliverables. However, I find it is a nicer way to code (after you get the hang of it), particularly because it helps me think of how to design/develop my classes. Also, if you factor in the time you spend unit testing and fixing defects discovered during functional and user testing, you will find that this style of working can actually save time in the end.
Writing tests first has several benefits. For example, writing tests first ensures that you write only functional code that will actually be used; this is based on the assumption that you have written code to satisfy the unit tests, which themselves are based on the acceptance tests specified earlier in our business requirements. Second, if your code passes the unit and acceptance tests, you are done with that part of the code. Third, it can help you design your classes better because when you write the test first, you are experiencing firsthand how your actual classes/methods will be used. Last, test first can also help you to refactor with confidence because you can retest your refactored code quickly through JUnit unit tests to ensure that the refactored code works as the original version did (assuming there is little or no change to the external interface, as defined on refactoring.com).
Although, unit testing is only one part of the overall testing that occurs in corporations, it is something that developers should always do. Other testing includes functional testing, user acceptance testing (UAT), system integration testing (also known as interface testing), stress/load testing, and more.
We will use JUnit to implement our acceptance tests. The following are sample files to demonstrate our class-naming convention for test classes:
· test/TimesheetListControllerTest.java
· test/TimesheetManagerTest.java
· test/ReminderEmailTest.java
I have chosen to keep our JUnit test classes in a separate test package (that is, com.visualpatterns.timex.test) because I believe this is a cleaner design. However, I've also seen other developers keep the JUnit test classes in the same directory as the code being tested. For example, in this scenario, our TimesheetListControllerTest.java would be placed in our controller package.
Agile - Building the Sample Application
XP and AMDD-Based Architecture and Design Modeling
IN THIS CHAPTER, WE FINALLY BEGIN to get into the technology side of things, so now begins the fun part.
In a truly iterative development environment, all the architecture and design issues would not necessarily be finalized up front. Refactoring (improving code without impacting its functionality) plays a big role in constant improvement to the initially established design because invariably you will find better ways to do something when you are actually coding. Furthermore, while the scope of the project can be defined up front, the user requirements can continue to evolve from iteration to iteration versus having everything locked-down up front. With requirements, the idea is to have a lot of interaction with the stakeholder and be able to ask ad hoc questions.
Although some work can be done up front, such as the user stories, high-level architecture, user interface prototypes, domain model, standards and so on, other design issues can be resolved in the iteration they are applicable to. Furthermore, "Using Hibernate for Persistent Objects,", "The Spring Web MVC Framework," writing tests first can also help with the design of your classes, so you don't have to have all the fine details of your classes figured out up front; in other words, you can take a just-in-time approach to design, so to speak.
However, some upfront design is bound to happen, perhaps in iteration 0 (perhaps when you are trying to demonstrate a proof-of-concept, which shows that the chosen technologies can work end-to-end, from the user interface to the database, for example).
In this chapter, I hope to provide you with an end-to-end approach using modeling and process guidelines provided by Agile Model Driven Development (AMDD; agilemodeling.com) and Extreme Programming (XP; extremeprogramming.org).
Design Approach and Artifact Choices
In the previous chapter, we looked at an XP-based approach to defining business requirements and working with the customer. In this chapter, we will drill down into some minimal architecture and design to help us get going with building Time Expression, using popular technologies such as Hibernate, the Spring Framework, the Eclipse SDK, and many other related tools such as Ant, JUnit, and more.
If you have come across the myth that XP programmers don't design or document, I hope this misconception will be cleared up by the end of this chapter, because it couldn't be further from the truth. Let me give you a preview of what I'm talking about.
Take a look at Figure 3.1, which shows some possible artifacts you can produce at the release or iteration level. Release-level artifacts are ones you produce prior to a new release; iteration-level artifacts are ones you produce prior to each iteration. These aren't all mandatory for every project, so we can pick and choose the ones we need. However, between Chapter 2, "The Sample Application: An Online Timesheet System," and this chapter, I have chosen to demonstrate as many of these as possible, and practical, for Time Expression. At the end of this chapter, I will show you another diagram that will tie together all the artifacts produced as a result of our efforts between the previous and this chapter (but don't cheat by looking now, because it is a detailed diagram and I don't want to overwhelm you at this point).
At the very least, what you will see in this chapter will give you one perspective. This process might or might not work for you. However, there must be some things good about these methodologies, because developers love them, and I have seen many successful projects as a result of these methods. Also, in our case, the artifacts we will produce in this chapter are essential to the rest of this book, and this process will help get us there.
As you can see from Figure 3.1, we have a few artifacts to produce in this chapter, so let's move forward. However, before we do, I want to provide two perspectives from real-world users of XP.
A project director working at a Fortune 50 company told me recently, "When we kick off an iteration, the first day of the iteration is usually spent reviewing stories and breaking them into tasks. The exercise of breaking them into tasks is truly a design session. What we ended up observing is that something like 20% of the developer's time, during an iteration, was spent in design. If you add all that time for all developers, across all iterations, it was a large numberwhich truly debunked the 'no design' comments."
To give you another perspective on the XP style of working, consider this statement from a senior architect at a well-established IT solutions company that has deployed more than a dozen successful projects using XP and AMDD techniques: "There is also another level of design that happens on an XP project which is at the daily level. Refactoring is a design activity. Although the iteration-kickoff design is an important step, it is the design work after the code is written that makes the difference between an OK design and a truly elegant one."
The difference with the XP approach, is that the architecture and design happens throughout the application's release cycle, not just up front. In other words, the application continues to evolve through the various iterations. The benefit of this approach is that the design is actually applicable to what you are building, not three to six months into development when the requirements could have changedsomething that is certainly possible in our fast-paced and ever-changing world today.
Free-Form Architecture Diagram
Figure 3.2 shows the high-level architecture for our sample application. Note that this has been converted to an electronic version from the whiteboard version we saw at the end of the previous chapter. Converting it to an electronic format is a personal preference; you could just as easily take a digital picture of the whiteboard version, but I personally like clean and readable diagrams.
The architecture is fairly straightforward. We have our standard three-tier web architecture with the client tier (web browser), middle tier (application server), and our data tier (database).
Also standard is the use of the model-view-controller (MVC) design pattern, as you find in most Java-based web frameworks these days. The controller is the point of entry of the HTTP/web request; it controls the model and the view. The model deals with data, which is obtained by the controller and passed to the view for rendering in a presentable way. In our case, the view will be written using JavaServer Pages (JSP).
What makes our architecture interesting isn't that it uses a MVC pattern, but rather what's in the middle tier, namely the Spring Framework and Hibernate, two technologies we will cover in detail later in the book. Hibernate, as you will see later, makes database persistence very easy because you can reference database tables and records as plain old Java objects (POJOs). The Spring Framework (springframework.org) provides many benefits, as well, especially when you're working with POJOs. For example, we will use the Spring MVC for our web framework because it makes for cleaner code (when compared to something like Struts). Another notable feature of the Spring Framework is the support for scheduling jobs rather than depending on an external scheduling service such as CRON or the Windows Scheduler. Of course, the core feature provided by the Spring Framework is the inversion of control (IoC) functionality, which we will learn about in later chapters.
Exploring Classes Using CRC Cards
Figure 3.3 shows the domain model . The domain model enables us to explore domain or business objects. The user stories will enable us to discover the web-based user interface controller classes. So, let's look at coming up with objects for the Timesheet List user story next, to see exactly how CRC cards work.Figure 3.4 shows the Timesheet List UI prototype . As I mentioned, we already know our user interface will be web based and will use the MVC paradigm. So, let's approach the discovery of our initial classes from the MVC perspective.
On the model part of the MVC, we already know some entity names for Time Expression from our domain model. For the controller part, we know the user story tag (Timesheet List, in this example) . Given these, we can now proceed with our initial class design using CRC cards.
In case you have been wondering, CRC stands for class, responsibilities, and collaborators. Table 3.1 shows the layout of a sample CRC card along with some explanations for the three components you see there. Note that although I have shown an electronic version, CRC cards can actually be done on basic 3" x 5" index cards and later translated into a class diagram (if needed).
CRC cards provide an informal object-oriented technique for discovering interactions between classes. I like CRC cards because they can be used in an informal session with developers or users to discover objects without the need for a computer. Furthermore, CRC cards can be used to develop a formal class diagram, if needed (something we will do later in this chapter).
Tables 3.2 through 3.4 show some sample CRC cards for the actual classes we will develop later in this book, to meet the requirements for the Timesheet List screen.
Application Flow Map (Homegrown Artifact)
In past projects, I have used a table similar to Table 3.5. This format is homegrown, in that it is something I came up with. I call it an application flow map because it shows me how a user interface will function (or flow) end to end. This technique also nicely maps the user stories to the view (the "V" in MVC), which maps to the controller and, finally, to the model objects.A Complementary Technique
In comparing this application flow map to techniques such as class diagrams or CRC cards, you will find that this map complements CRC cards and class diagrams. CRC cards list, among other things, responsibilities of each class, which is lacking in the application flow map. Class diagrams on the other hand, show relationships, cardinality, behavior (methods), attributes, and possibly more, which are more details than I like to have in this map.
By putting together classes in a textual and table format, we could also search for class names (in a large system, for example) and also sort these easily using a spreadsheet program or command-line utilities.
Extending the Application Flow Map with CRUD Columns
This table can also be altered for use with non-UI stories such as the Reminder Email: Employee user story. For example, the view and controller class columns can be replaced with a single column named Job, for instance.
Furthermore, you can extend this table by splitting the Tables Impacted column into four separate CRUD (create, read, update, delete) columns. This not only shows which tables are impacted, but how they are impacted, by the various collaborator classes. By adding CRUD columns, you essentially provide end-to-end flow of a user story (from the view to the database and back) in one row of our table.
UML Class Diagram
Next, we will look at a rudimentary class diagram. This is an optional step in my opinion (see sidebar on UML diagrams) because our CRC cards and application flow map provide us with enough information to move forward with coding. However, class diagrams can be a good thing when used appropriately.UML Package Diagram
For our sample application, Time Expression, we will use the prefix com.visualpatterns.timex for our package name.
If you have worked with Java already, you probably know that the first part of the package name is typically tied to an organization's domain name, just used backwards. For example, com.visualpatterns is the reverse for visualpatterns.com, which happens to be my website. The timex portion of our package name is derived from the name of our sample application. The remainder, the suffixes, for our package names are shown in Figure 3.6, a rudimentary UML package diagram.
As you might guess, the controller package will have controller-related classes in it. The job package will contain our email reminder job. The util package contains common and/or utility code.
Last but not least, the test package will contain our unit test code. Although I have chosen to place our test classes in a separate package, many developers prefer keeping the test classes in the same directory as the implementation code they are testing. This is a matter of preference, but in my opinion, having a separate package/directory for the test classes keeps things nice and clean in the actual implementation package directories.
Directory Structure
Figure 3.7 shows the directory structure we will use for our sample application. This should look pretty straightforward and familiar; the most notable subdirectories here are src, build, lib, and dist. and the directories relevant to each chapter will be discussed in a bit more detail, when needed. Meanwhile, Figure 3.7 provides a brief description for all the key directories.
Sample File Names
Given our directory structure shown in Figure 3.7, we can now come up with some sample filenames for the classes we discussed in this chapter. For example, for the Timesheet List screen we discussed earlier in this chapter, we will most likely end up with the following files under the timex/src/java/com/visualpatterns/timex/ directory:End-to-End Development Steps
Given what we have learned in this chapter so far, we can put together the steps that will be required to develop (code) for our first user story, from the web UI to the database, and back. Here are tasks that will most likely be required to complete the first user story:
-
Set up our environment including the JDK, Ant, and JUnit
-
Write test and implementation classes for model package
- Write test and implementation classes for controller package
Acceptance Tests
Acceptance tests can serve as our detailed requirements as they do in many Agile style projects. One example is a list of valid operations a user can perform on a given screen. The idea of using acceptance tests as requirements is feasible because these tests are something our customer expects our application to conform to. For our purposes, we will use them only for our unit tests; however, it is becoming more and more common in the real world to use acceptance tests as detailed requirements.
The following sections are our list of acceptance tests and something we will implement for the user stories we will develop. In the real world, these types of acceptance tests would be provided by the customer.
Sign In
- The employee id can be up to 6 characters. The password must be between 8 and 10 characters.
- Only valid users can sign in.
Timesheet List
- Only a user's personal timesheets can be accessed.
Enter Hours
-
Hours must contain numeric data.
-
Daily hours cannot exceed 16 hours. Weekly hours cannot exceed 96 hours.
-
Hours must be billed to a department.
-
Hours can be entered as two decimal places.
- Employees can view and edit only their own timesheets.
Other Considerations
As I mentioned earlier, we need to do just enough architecture and design to get us going. Although we did a reasonable amount of architecture and design in this chapter, there are a lot of things we haven't discussed yet but will in later chapters, such as the following:
- Application security
- Transaction management .We will see how to programmatically implement transaction management using Hibernate.
- Exception handling .We will look at handled and unhandled exceptions and provide some guidance on when to use one versus the other.
- Other features Features required for Time Expression such as scheduling jobs and sending emails..
Big Design Up Front Versus Refactoring
According to Martin Fowler (refactoring.com), refactoring "is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior." Many developers have been refactoring code for years, but Martin Fowler gave it a formal name (and I'm glad he did).
As you begin to code an application, you will invariably find better ways to do things than you might have originally thought of (before coding began). For example, this could include removal of redundant code or cleaning up of code. Hence, I am a big believer that refactoring should always be an open option, not just for code but also for database design, architecture, documentation, build/integration scripts, and more. It also alleviates the burden of figuring out the entire design and process of an application up front.
For example, I recently came across a portion in an essay on the agiledata.org website, which helps summarize how I feel about this subject; this portion states that "Agile developers iterate back and forth between tasks such as data modeling, object modeling, refactoring, mapping, implementing, and performance tuning."
Take this book, for example. This is essentially a project for me as I'm developing a sample application from scratch and a book alongside it. Although I have done some upfront planning, I don't have 100% of the answers figured out, but I am not worried because I can refactor the architecture, design, code, or process used for Time Expression in later chapters because I want to make progress now instead of spending too much time trying to think of every possible scenario that could go wrong.
In short, you should definitely do some initial architecture and design, but keep in mind that if there is a way to improve something that adds value, such as simpler or cleaner code, and if it is not too late in the process (for example, the day of acceptance tests or deployment), you should go ahead and refactor!
Agile - Sample Application
Exploration Phase
The Sample Application: An Online Timesheet System
IN THE REAL WORLD, A NEW SOFTWARE development project is typically initiated because there is some sort of a customer need, problem, or process optimization. This need can be from an internal group or an external party (for example, interfacing with an external partner system or consumer demand for a product). After a problem or need is identified, there is typically some form of a project kickoff meeting to better define the requirements.
As I mentioned in the previous chapter, this book tries to follow a flow similar to how a real-world project might flow. In this book, we will pretend that we have a requirement from an internal group (a fictional customer) and use this requirement to build a sample application named Time Expression.
I considered several types of applications to use as an example in this book; in the end I settled on a rudimentary timesheet system because I believed that it was an application most readers would be able to relate to. For example, you might be an employee or consultant who works by the hour, and you submit your timesheet online (and also get it approved online, and so on).
Our sample application, Time Expression, will have a user interface (UI) as well as some background processing. The UI will be web based and will contain screens that provide the capability to enter hours worked, approve timesheets, run management reports, and more. The background processing will include a weekly (scheduled) batch job that is automatically run to send out a reminder email.
Business Requirements
I mentioned earlier that our fictional customer requires a simple online time entry and approval system. Let's go into a bit more detail here.
It is always a good idea to define what business problem is being solved, whom it is being solved for, and why our solution is important to the customer. In addition, it is important to understand what the customer's expectations are: for example, when is the solution needed, and what is the project scope.
Let's assume that a fictional organization wants to build a timesheet system to manage its hourly staff. To get things started, we can define the problem statement as follows.
Problem Statement
Our employees currently submit their weekly hours worked using a paper-based timesheet system that is manually intensive and error-prone. We require an automated solution for submitting employee hours worked, in the form of an electronic timesheet, approving them, and paying for the time worked. In addition, we would like to have automatic notifications of timesheet status changes and a weekly reminder to submit and approve employee timesheets.
Given our general problem statement, we can break this down into the following feature set or business requirements; this process could be considered a part of use case analysis, in the Unified Modeling Language (UML) world:
-
Hourly employees should be able to sign in to a web application (once or more each week) and enter their hours for each day of a given week. Along with the hours, the employee must select which department the hours are being billed to.
-
Employees will be required to submit their timesheets each week.
-
An employee's manager is notified of successfully submitted timesheets. The manager must then approve or disapprove the timesheets.
-
After a timesheet is approved or disapproved, a notification is sent back to the employee indicating the updated status of the timesheet. If the timesheet is approved, an email is also sent to the accounting department to process the paycheck for the given employee.
-
All users of Time Expression will have one or more relevant reports available to them.
-
A weekly reminder email will be sent out to employees who have not submitted their timesheets. Another reminder email is sent to managers who have employee timesheets pending approval.
Now that we have some basic business requirements, we can proceed with our software development process.
Software Development Methodology
Every project, small or large, should have some basic structure or process (methodology) it must follow. This could be a simple one-page checklist or a slightly more formal process. Having no process at all is bad, but too much is equally bad. Finding the right balance depends on the customer's needs and the project size, but in summary, I lean toward having less process with minimal (and "good enough") documentation requirements, rather than having a bloated process that can bog down the customer and developers in paperwork and procedures. In this chapter, I'll provide a basic software development process based on XP and AMDD.
Overview of XP and AMDD
XP and AMDD provide some fundamental guidelines for building software applications effectively and rapidly. XP and AMDD are complementary methods because XP provides a disciplined, full life cycle software development approach that stresses customer satisfaction. AMDD, on the other hand, generally provides effective practices for modeling and documentation, but goes a lot further by providing a wealth of additional best practices that can be tailored to each software development project.
The Exploration Phase (Beck, 2000) typically involves a combination of exploratory activities that help you better understand the customer's needs and subsequently how the resulting application will be designed and built. The following are some examples of activities that might take place in this phase of the project.
-
Domain model A domain model helps to define major business concepts (entities) and the relationships among them.
-
User interface prototypes and storyboard These are initial screen mockups to get a feel for how the customer visualizes the application. The storyboard is the flow of the screens.
-
User stories A few user stories get the project started and make up the first release or version of the application. User stories (similar to shall statements in other methods) are written by the customer in a brief sentence or two explaining what the customer wants the application to do. Note that the number of user stories you gather up front will depend on the project, but you should have enough to make a good and useful release.
-
Scope definition It is important to define the scope of the project up front so that you know what needs to be developed and what can be deferred. It also clarifies the customer's expectations.
-
Analysis : This can include a combination of whiteboarding, an informal architectural diagram, a glossary, and more.
Planning Phase
Planning can mean different things to different people. For me, it should at least include the following:
-
Release plan This is essentially a plan for the next release (version) of a system and can easily be put together using a spreadsheet program or even a word processing program and/or HTML table. It lists all the user stories that will be included in the next release of the system, grouped together in several iterations. Releases are typically of fixed length, anywhere between one to three months; two months is typically an optimal size.
-
Iteration plan An iteration plan is developed prior to each iteration. It includes the user stories the customer wants implemented in the next iteration. Iterations are typically of fixed length, anywhere between one to three weeks; two weeks is typically an optimal size.
-
Define standards (code, database, process) Before beginning any development, it is a good idea to standardize such things as coding conventions, database naming conventions, processes (build, integrate, deploy), and more.
Active Stakeholder Participation
According to the agilemodeling.com website, "Active Stakeholder Participation is an expansion of eXtreme Programming (XP)'s On-Site Customer that describes the need to have on-site access to people, typically users or their representatives, who have the authority and ability to provide information pertaining to the system being built and to make pertinent and timely decisions regarding the requirements, and prioritization thereof."
Given this, I would recommend to always do release and iteration planning with the customer and developers. Remember, successful projects are typically ones where the customer is actively involved (hence, the phrase Active Stakeholder Participation).
For more details on active stakeholder participation, you may want to read the following essay on the AM website: agilemodeling.com/essays/activeStakeholderParticipation.htm.
Iterations to Release Phase (Building Software in Increments)
Iterative development is a term you are probably familiar with. However, understanding of iterative development and what each iteration should include varies from person to person and from methodology to methodology.
For me, iterative development means that each iteration includes design, coding, user acceptance, and deployment of "production ready" code. This code can be deployed to the production environment or, if you are in a large corporation and deploying to production frequently is not practical, perhaps deploying to the acceptance environment will do, so long as it is accepted by the customer, thus allowing you to move on to the next iteration. To summarize, each iteration might include the following activities:
-
Development tasks, estimates by developers, and a plan for the next iteration.
-
Ad hoc Q & A between developers and the customer.
-
Design CRC cards, UML diagrams, and so on.
-
Code test first, refactor code/database/architecture as required, optimize later.
-
User acceptance testing (UAT).
-
Deploy iteration to production (or UAT); this step is also referred to as a small release.
By delivering iterations in this fashion, you can incrementally build the next release of an application. For example, we might estimate three months for a given project and break it down into two-week iterations, resulting in approximately six iterations.
The bottom line at the end of each iteration is that the project should be deliverable; in other words, the small releases should contain production-ready (stable) code, even it provides only a subset of the complete system.
Scope of Project
The scope of project can be defined in many formats. Sometimes it is as simple as a oneto two-line paragraph described by the customer, or it can be more structured using diagrams. Many organizations go one step further and sign service level agreements (SLAs) with the development team. Also, functional and nonfunctional requirements discussions can also occur to help define the scope.
In the past, I have used a table to show what is included in the scope and what is deferred (or excluded) from scope, as demonstrated in Table 2.1, a sample scope table for Time Expression.
Maintenance
This is where the application enters a maintenance state. This phase might include training for the user, minor enhancements/fixes (in the form of user stories), as needed. Or the customer might want to do another major release, in which case you would start back from the Exploration Phase mentioned earlier in this chapter.
Applying XP and AMDD to Our Sample Application
Now that we have looked at some background on a generic software development process, let's apply parts of this to our sample application.
Domain Model
Let's start our domain model, which essentially has all the data entities and their relationships, but no attributes. This helps to define some initial domain concepts and their relationships to each other. The domain model is typically sketched while working with domain experts and people with business knowledge, such as business users and analysts.
Figure 2.2 shows the domain model for our application, Time Expression. As you can see, our domain model has a simple design because it contains the bare-minimum number of entities to get us going while following a clean design. Again, we just need a simple domain model to start with, something good enough for us to move forward with, which we have now.
Figure 2.2. Domain model for Time Expression.
User Interface (UI) Prototype
Now that we have a fairly good idea of the features our customer is looking for in Time Expression, we can rapidly mock up some prototype screens to allow the customer to test drive the mocked web application.
By developing prototype screens early on, you put a face to the application, which gets people excited and motivated to get the application built. This is also a good way to eliminate many of the cosmetic changes up front (such as fonts, colors) and come up with an agreed upon consistent look and feel that can be implemented using cascading style sheets (CSS). Furthermore, you can use prototypes to model the business process and subsequently use the same prototypes to define the users' stories (covered later in this chapter).
Figures 2.3 through 2.10 show what the various screens in the Time Expression application will look like. We will begin designing this application in the next chapter; then, in subsequent chapters, we will get our environment set up and begin developing some code!
Figure 2.3. Sign-In screen.
Figure 2.4. Timesheet List screen.
Figure 2.5. Enter Hours screen.
Figure 2.6. Print Hours screen.
Figure 2.7. Approve Timesheets screen.
Figure 2.8. Mark Paid screen.
Figure 2.9. Report: Staff Hours screen.
Figure 2.10. Report: Overall Summary screen.
At this point, let's keep these screens as simple HTML (versus JSP) files so that we can pull them up locally in a browser instead of having to run them in a Java web server or pull them up in a JSP/HTML editor each time. When working with a customer, it is a good idea to keep technology out of the picture, as much as possible, until you are ready for developmentthis keeps things simple, so you can avoid any "technical difficulties" and instead focus on the business requirements at hand.
Managing Customer Expectations During UI Prototyping
Although UI prototype provides significant benefits, it is important to manage the customer's expectations in this stage, as well. For example, I have run across two problems. First, when customers see prototype screens, they might believe the application is mostly developed and almost ready to be deployed. However, as developers, we know there is a lot more to application development than mocked up screens. Second, user prototyping can get out of hand if the customer is picky about fonts, button placements, and other UI aesthetics. Still, the customer should always come first because they are typically paying for the application, and so you should try to find the right balance when managing a customer's expectations. Of course, one effective way of getting around this management of expectations is to do hand-drawn UI sketches instead of prototyping. This keeps thing simple because these sketches can be drawn on paper or the whiteboard.
Storyboard
A storyboard, also called a UI flow diagram or website map, is essential to show a navigation map of the various screens. Figure 2.11 shows the storyboard for our sample application. As you can guess from our storyboard, after a user is signed in to the system, the user is directed to an initial screen designated for the user's role type. Users belonging to either the Employee and Manager role have additional functionality that can be accessed from the initial screens.
Figure 2.11. Storyboard (also known as a UI flow diagram).
User Stories
Given the business requirements and UI prototypes defined for Time Expression earlier in this chapter, we can now define a set of user stories for our application. As explained earlier in this book, I decided to use XP/AMDD; therefore, you see the use of the term user story versus use case. Although these serve similar purposes, user stories tend to be shorter than use casesfor example, one to three sentences each. The remaining details can be discussed between the developer and the customer when the developer begins working on a given user story in the planned iteration; hence, the term active stakeholder participation.
Use cases come in many formats themselves. The three I'm familiar with are formal, brief, and casual. The casual format is probably closest to a user story because it is short and informal. Formal use cases can entail a page or two of requirements with preconditions, postconditions, success/basic path, failure/alternative path, and other sections for each use case. The reason I have described use case and their formats here is because certain organizations define essential use cases (or even business requirements with "shall" statements) first, and then later break each use case down into one or more (maybe even several) user stories using our guideline of one- to three-day development per user story or development task.
We will use user stories in this book to not only define the requirements, but also to name our Java classes, using the story name/tag, and create acceptance tests. Table 2.2 shows the user stories with the priority and initial estimate to complete. Note that the user stories you might find in the real world might be a bit more detailed than what I have shown in Table 2.2; however, given the simplicity of Time Expression, these work fine for us.
|
# |
Story Name (Tag) |
Story Description |
Priority |
Points (estimate) |
|
|---|---|---|---|---|---|
|
1 |
Enter Hours |
User can enter hours worked and save this data. |
1 |
2 |
|
|
2 |
Timesheet |
List Employee can see a list of timesheets previously entered and click the ones that can be modified. |
1 |
1 |
|
|
3 |
Sign In |
User can sign in to system using a valid employee id and password. |
2 |
1 |
|
|
4 |
Sign Out |
Users can sign out of system to end current session. |
2 |
1 |
|
|
5 |
Reminder Email: Employee |
A reminder email is sent every Friday at 2 p.m. to employees who have not submitted their timesheet yet. |
2 |
1 |
|
|
6 |
Print Timesheet |
Employee can print timesheet using best possible formatting in browser and automatic display of print dialog box. |
3 |
1 |
|
|
7 |
Report: My Hours |
Employee can run a report named "My Hours" to view/print summary of weekly hours. |
3 |
1 |
|
|
8 |
Submit Timesheet |
User can submit timesheet after hours have been entered; submittal email is sent to Manager. |
3 |
1 |
|
|
9 |
Report: Staff Hours |
Manager can run a report named Staff Report to view a summary of a given week's hours for all employees under Manager. |
4 |
1 |
|
|
10 |
Report: Overall Summary |
Executive can run a report named Overall Summary to view a summary of a given week's hours for all Managers in company. |
4 |
2 |
|
|
11 |
Timesheet Approval |
Manager can approve/disapprove timesheet;notification email sent to Employee and Accounting department. |
5 |
1 |
|
|
12 |
Timesheet Payment |
Accounting can indicate that Employee has been paid. |
5 |
1 |
|
|
13 |
Reminder Email: Manager |
A reminder email is sent every Friday at 4 p.m. to managers who have timesheets pending approval. |
5 |
1 |
|
|
Total Points: |
15 |
Incidentally, a good book to check out on user stories is Mike Cohn's User Stories Applied: For Agile Software Development (Addison-Wesley Signature Series, 2004).
The estimates shown in Table 2.2 are initial estimates, or sizing. The developer provides more accurate estimates at the beginning of the iteration when the user story will be developed, because the user story can be broken down into development tasks to better size the time required to complete the entire user story. Incidentally, I have come across real-world projects where they did not do the breaking down of user stories into tasks, nor did they size the user stories during iteration planning. The reason for this was because sometimes the user story priorities changed or the user story itself changed, so the upfront work was for nothing. Instead, they picked two to three stories on day one of a new iteration and only estimated those.
Points (last column of Table 2.2) are some unit of measure relative to the given project. For example, 1 point could equal 1 regular workday, 1 ideal workday, 1 week or another periodwhatever the customer and developers agree on. Whatever each point might measure is then used to provide estimates to the customer.
Ideal (development) days are a good way to estimate projects because it factors in planned and unplanned events (for example, meetings, computer problems, sick leave, and so on). The difference between a regular day and an ideal day is referred to as the load factor.
A load factor, typically between 2 and 4, is a number you multiply your initial estimate by to come up with an ideal day. For example, I like to use a load factor of 3 for projects where I have a good understanding of the business requirements and technologies. (Note: If you believe there are risks involved, such as a learning curve related to a new technology, you can use a higher number, such as 4 or even 5.) For example, if we know a development task will take me approximately 8 hours of uninterrupted, totally focused, heads-down time, we can multiply that by 3 (that is, 8 * 3) and come up with 24 ideal hours or 3 ideal days (assuming a 8-hour work day).
In this book, we will develop the Enter Hours and Timesheet List (items 1 and 2 in Table 2.2; both with priority 1). So, if we use these two screens as example, it would take 9 actual days to complete these screens (that is, 3 ideal days times the load factor of 3).
Release (and Iteration) Plan
After the customer (end user and/or business analyst) has defined the user stories, the customer and development project manager (and/or developer) can put together a release plan for the next release or version of the application.
A release plan is essentially a project plan listing various system releases and the dates for each release. In this book, we will assume that we have only one releasefor example, v1.0.
Releases are typically small, about 1 to 3 months in length. Each release consists of a set of user stories the customer wants implemented in that release. Each release is then further broken down into iterations.
Iterations range between 1 to 3 weeks in length. Each iteration contains a list of user stories chosen from the set of user stories for the given release that the customer wants implemented in that iteration (along with defect fixes from previously failed acceptance tests).
Based on the user stories we defined earlier in this chapter, we can come up with an initial release plan, shown in Table 2.3, to incrementally build release v1.0 of our application.
|
Iteration |
Features |
Release Date |
|
|---|---|---|---|
|
0 |
Environment setup (JDK, Ant, JUnit) and database connectivity demo using Hibernate. |
23-Dec-06 |
|
|
1 |
Small releaseAll priority 1 user stories. |
12-Jan-07 |
|
|
2 |
Small releaseAll priority 2 user stories. |
26-Jan-07 |
|
|
3 |
Small releaseAll priority 3 user stories. |
09-Feb-07 |
|
|
4 |
Small releaseAll priority 4 user stories. |
23-Feb-07 |
Our release plan does not use priority 5 user stories because these will be pushed off to release 2 of our application. Of course, this is all fictional and many of the examples we have looked at so far, such as the iteration and release plans, are for demonstration purposes only. In the real world, you are bound to see more detailed plans.
After the release plan containing the various iterations is defined for the next release of the software, the developer can begin working on the first iteration.
Prior to each iteration, the customer and development staff get together for an iteration-planning meeting, the outcome of which is an iteration plan for the next iteration. The customer picks the user stories that will be developed in the next iteration. The developers break down each user story into individual development tasks required to implement the user story. This is done so that each development task can be assigned to a developer, but more importantly, the tasks can be used to more accurately estimate the total development effort for the given user story and, in turn, the next iteration.
If the total estimate or points (to implement all chosen user stories for the next iteration) exceeds the total points implemented in the previous iteration (known as the Project Velocity in Extreme Programming), the customer must choose which user stories (or defect fixes) to defer to a future iteration or release. If the opposite is truethat is, there is room to get more done in the next iteration, the customer may add additional user stories, defect fixes, or enhancements, if needed.
For our purposes in this book, I have skipped including a sample iteration plan because this book is more about development than process. Also, formats of an iteration (and release) plan can vary, so instead I chose to leverage the release plan (see Table 2.3) and group our user stories by priority in it instead of breaking them down individually in each iteration plan.
Glossary
This is probably a good time for us to define a glossary for Time Expression.
A glossary is essentially a set of common terms, or project vocabulary, that everyone agrees on for the project. This list can include business terms (for example, Timesheet and Approved) or technical terms (for example, Entity, used while discussing the logical data model). The obvious benefit of a glossary is that it gets everyone in agreement with the terminology and definitions of each term to avoid any confusion. (We have enough of that already given the terminology/acronym madness that exists in our industry.)
-
Accounting The accounting department/staff.
-
Approved Status of a timesheet when a Manager approves a previously submitted timesheet.
-
Employee A person who works on an hourly basis and reports to a manager.
-
Executive An officer of the company, such as CEO, CFO, or COO.
-
Hour A full hour of billable work that can be entered into a timesheet and the employee can get paid for.
-
Manager Direct supervisor of an employee.
-
Paid Status of a timesheet when the accounting department has issued a check.
-
Period Ending Date This is the last day of each week (Sunday, in our case).
-
Pending Status of a timesheet until the user submits it.
-
Submitted Status of a timesheet when an employee has submitted a timesheet. Timesheet is "locked" from further changes by employee.
-
Week A 40-hour workweek from Monday through Friday.
Whiteboard Architecture
By now, we have enough information to put together an informal architecture diagram. Figure 2.12 shows a high-level architecture diagram for Time Expression (on an indispensable tool of the trade, the whiteboard). By establishing this diagram, the developers and customer can agree on major technologies (for example, Java, database, web/app server) that will be used to build Time Expression.
Figure 2.12. An informal, high-level architecture on a whiteboard.
We will use an electronic and more detailed version of this architecture diagram in the next chapter to help us go one level deeper into the design of the applications. Converting whiteboard diagrams or CRC cards to electronic formats are my personal preference because legibility isn't a real concern with electronic artifacts. However, you could simply digitize artifacts such as whiteboard drawings and CRC cards via tools such as a digital camera and scanner, respectively.
Although I have some fundamental practices I use on all projects, I typically pick and choose what applies to each project and customize the software development process based on the needs of that project and customer. For example, in our sample project/application in this book, Time Expression, I have used several of the techniques described next and shown in Figure 2.1 (refer to agilemodeling.com/essays/agileModelingXPLifecycle.htm for details). Note that although I have adopted the XP and AMDD way, there might be a few spots where I customize these methods (Project kick-off, for example) to accommodate what we need for Time Expression.
TOGAF - The Way Forward?
So what is TOGAF?...
The Open Group defines TOGAF as a framework - a detailed method and a set of supporting tools for developing IT and Enterprise Architecture.
There are many architecture frameworks, but TOGAF is unique in containing a method for developing architecture - the TOGAF Architecture Development Method (ADM). The ADM can be used with other popular frameworks and so we might call it framework-agnostic.
TOGAF is the result of best practice, as gathered by The Open Group's Architecture Forum. Consequently, TOGAF's great strength is that it is non-proprietary and free to use. However, this does mean that architects need to customise and tailor TOGAF to their organisation's specific needs.
For more information visit the Open Group - http://www.opengroup.org/