Tuesday, July 31, 2007

Some Words About JUnit Testing

Testing is not a very interesting thing sometimes. Some developers use standard output or debugger in order to test their classes. But there is another way...
In this article you’ll find the introduction into JUnit library. JUnit framework makes the process of test-writing much easier.
To show you the power of JUnit let me create the small class in Java and write some test cases for it. Consider the following code:
public class MathFunc {
private int variable;

public MathFunc() {
variable = 0;
}
public MathFunc(int var) {
variable = var;
}

public int getVariable() {
return variable;
}
public void setVariable(int variable) {
this.variable = variable;
}

public long factorial() {
long result = 1;
if (variable > 1) {
for (int i=1; i<=variable; i++)
result = result*i;
}
return result;
}

public long plus(int var) {
long result = variable + var;
return result;
}
}

At first, you have to create the class which extends junit.framework.TestCase. The proper constructor also must be defined. This constructor has to provide String parameter to the parent class’ constructor. At last, you have to write as many test methods as you want:

public class TestClass extends TestCase {
public TestClass(String testName) {
super(testName);
}

public void testFactorialNull() {
MathFunc math = new MathFunc();
assertTrue(math.factorial() == 1);
}

public void testFactorialPositive() {
MathFunc math = new MathFunc(5);
assertTrue(math.factorial() == 120);
}

public void testPlus() {
MathFunc math = new MathFunc(45);
assertTrue(math.plus(123) == 168);
}
}

Method assertTrue checks the parameter’s value for “true” result. So, we can compare the output value of some method to the expected value. Methods assertEquals, assertFalse, assertNull, assertNotNull, assertSame are also useful ones.
In order to combine few tests together you can use TestSuite class. Just add some tests with addTest method. Finally, you have to use TestRunner to execute tests. I prefer to use junit.textui.TestRunner (there are also graphical implementations - junit.swingui.TestRunner, junit.awtui.TestRunner). The main method of the test class looks like this:

public static void main(String[] args) {
TestRunner runner = new TestRunner();
TestSuite suite = new TestSuite();
suite.addTest(new TestClass(“testFactorialNull”));
suite.addTest(new TestClass(“testFactorialPositive”));
suite.addTest(new TestClass(“testPlus”));
runner.doRun(suite);
}

Output after execution:

Time: 0,02
OK (3 tests)

For the testing of more complex classes you can use methods setUp and tearDown. The first method initializes several instances of the specified class in order to use them in several test cases. The second method serves to release unused resources after tests have passed.
I hope this article will help you a little.



Technorati Tags: , , ,

Friday, July 27, 2007

Using OSF Layers in Your JWeb Application

This article will discuss one strategy for combining frameworks using three popular open source frameworks. For the presentation layer we will use Struts; for our business layer we will use Spring; and for our persistence layer we will use Hibernate. You should be able to substitute any one of these frameworks in your application and get the same effect. Figure 1 shows what this looks like from a high level when the frameworks are combined.





Figure 1. Overview of framework architecture with Struts, Spring, and Hibernate.

Application Layer

Most non-trivial web applications can be divided into at least four layers of responsibility. These layers are the presentation, persistence, business, and domain model layers. Each layer has a distinct responsibility in the application and should not mix functionality with other layers. Each application layer should be isolated from other layers but allow an interface for communication between them. Let's start by inspecting each of these layers and discuss what these layers should provide and what they should not provide.

At one end of a typical web application is the presentation layer. Many Java developers understand what Struts provides. However, too often, coupled code such as business logic is placed into an org.apache.struts.Action. So, let's agree on what a framework like Struts should provide. Here is what Struts is responsible for:

- Managing requests and responses for a user.

- Providing a controller to delegate calls to business logic and other upstream processes.

- Handling exceptions from other tiers that throw exceptions to a Struts Action.

- Assembling a model that can be presented in a view.

- Performing UI validation.

Here are some items that are often coded using Struts but should not be associated with the presentation layer:

- Direct communication with the database, such as JDBC calls.

- Business logic and validation related to your application.

- Transaction management.

Introducing this type of code in the presentation layer leads to type coupling and cumbersome maintenance.

The Persistence Layer

At the other end of a typical web application is the persistence layer. This is usually where things get out of control fast. Developers underestimate the challenges in building their own persistence frameworks. A custom, in-house persistence layer not only requires a great amount of development time, but also often lacks functionality and becomes unmanageable. There are several open source object-to-relational mapping (ORM) frameworks that solve much of this problem. In particular, the Hibernate framework allows object-to-relational persistence and query service for Java. Hibernate has a medium learning curve for Java developers who are already familiar with SQL and the JDBC API. Hibernate persistent objects are based on plain-old Java objects and Java collections. Furthermore, using Hibernate does not interfere with your IDE. The following list contains the type of code that you would write inside a persistence framework:

- Querying relational information into objects. Hibernate does this through an OO query language called HQL, or by using an expressive criteria API. HQL is very similar to SQL except you use objects instead of tables and fields instead of columns. There are some new specific HQL language elements to learn; however, they are easy to understand and well documented. HQL is a natural language to use for querying objects that require a small learning curve.

- Saving, updating, and deleting information stored in a database.

- Advanced object-to-relational mapping frameworks like Hibernate have support for most major SQL databases, and they support parent/child relationships, transactions, inheritance, and polymorphism.

Here are some items that should be avoided in the persistence layer:

- Business logic should be in a higher layer of your application. Only data access operations should be permitted.

- You should not have persistence logic coupled with your presentation logic. Avoid logic in presentation components such as JSPs or servlet-based classes that communicate with data access directly. By isolating persistence logic into its own layer, the application becomes flexible to change without affecting code in other layers. For example, Hibernate could be replaced with another persistence framework or API without modification to the code in any other layer.

The Business Layer

The middle component of a typical web application is the business or service layer. This service layer is often the most ignored layer from a coding perspective. It is not uncommon to find this type of code scattered around in the UI layer or in the persistence layer. This is not the correct place because it leads to tightly coupled applications and code that can be hard to maintain over time. Fortunately, several frameworks exist that address these issues. Two of the most popular frameworks in this space are Spring and PicoContainer. These are referred to as microcontainers that have a very small footprint and determine how you wire your objects together. Both of these frameworks work on a simple concept of dependency injection (also known as inversion of control). This article will focus on Spring's use of setter injection through bean properties for named configuration parameters. Spring also allows a sophisticated form of constructor injection as an alternative to setter injection as well. The objects are wired together by a simple XML file that contains references to objects such as the transaction management handler, object factories, service objects that contain business logic, and data access objects (DAO).

The way Spring uses these concepts will be made clearer with examples later in this article. The business layer should be responsible for the following:

- Handling application business logic and business validation

- Managing transactions

- Allowing interfaces for interaction with other layers

- Managing dependencies between business level objects

- Adding flexibility between the presentation and the persistence layer so they do not directly communicate with each other

- Exposing a context to the business layer from the presentation layer to obtain business services

- Managing implementations from the business logic to the persistence layer

The Domain Model Layer

Finally, since we are addressing non-trivial, web-based applications we need a set of objects that can move between the different layers. The domain object layer consists of objects that represent real-world business objects such as an Order, OrderLineItem, Product, and so on. This layer allows developers to stop building and maintaining unnecessary data transfer objects, or DTOs, to match their domain objects. For example, Hibernate allows you to read database information into an object graph of domain objects, so that you can present it to your UI layer in a disconnected manner. Those objects can be updated and sent back across to the persistence layer and updated within the database. Furthermore, you do not have to transform objects into DTOs, which can get lost in translation as they are moved between different application layers. This model allows Java developers to work with objects naturally in an OO fashion without additional coding.

First, we will create our domain objects since they will interoperate with each layer. These objects will allow us to define what should be persisted, what business logic should be provided, and what type of presentation interface should be designed. Next, we will configure the persistence layer and define object-to-relational mappings with Hibernate for our domain objects. Then we will define and configure our business objects. After we have these components we can discuss wiring these layers using Spring. Finally, we will provide a presentation layer that knows how to communicate with the business service layer and knows how to handle exceptions that arise from other layers.

Conclusion

This article covers a lot of ground in terms of technology and architecture. The main concept to take away is how to better separate your application, user interface, persistence logic, and any other application layer you require. Doing this will decouple your code, allow new code components to be added, and make your application more maintainable in the future. The technologies covered here address specific problems well. However, by using this type of architecture you can replace application layers with other technologies.

Tuesday, July 24, 2007

Data Validation in Hibernate

While it's important to build data validation into as many layers of a Web application as possible, it's traditionally been very time-consuming to do so, leading many developers to just skip it - which can lead to a host of problems down the road. But with the introduction of annotations in the latest version of the Java™ platform, validation got a lot easier. In this article, author shows you how to use the Validator component of Hibernate Annotations to build and maintain validation logic easily in your Web apps.

Java SE 5 brought many needed enhancements to the Java language, none with more potential than annotations. With annotations, you finally have a standard, first-class metadata framework for your Java classes. Hibernate users have been manually writing *.hbm.xml files for years (or using XDoclet to automate this task). If you manually create XML files, you must update two files (the class definition and the XML mapping document) for each persistent property needed. Using HibernateDoclet simplifies this (see Listing 1 for an example) but requires you to verify that your version of HibernateDoclet supports the version of Hibernate you wish to use. The doclet information is also unavailable at run time, as it is coded into Javadoc-style comments. Hibernate Annotations, illustrated in Listing 2, improve on these alternatives by providing a standard, concise manner of mapping classes with the added benefit of run-time availability.
Listing 1. Hibernate mapping code using HibernateDoclet

/** 
* @hibernate.property column="NAME" length="60" not-null="true"
*/
public String getName() {
return this.name;
}

/**
* @hibernate.many-to-one column="AGENT_ID" not-null="true" cascade="none"
* outer-join="false" lazy="true"
*/
public Agent getAgent() {
return agent;
}

/**
* @hibernate.set lazy="true" inverse="true" cascade="all" table="DEPARTMENT"
* @hibernate.collection-one-to-many class="com.triview.model.Department"
* @hibernate.collection-key column="DEPARTMENT_ID" not-null="true"
*/
public List getDepartment() {
return department;
}

If you use HibernateDoclet, you won't be able to catch mistakes until you generate the XML files or until run time. With annotations, you can detect many errors at compile time, or, if you're using a good IDE, during editing. When creating an application from scratch, you can take advantage of the hbm2ddl utility to generate the DDL for your database from the hbm.xml files. Important information -- that the name property must have a maximum length of 60 characters, say, or that the DDL should add a not null constraint -- is added to the DDL from the HibernateDoclet entries. When you use annotations, you can generate the DDL automatically in a similar manner.

While both code mapping options are serviceable, annotations offer some clear advantages. With annotations, you can use constants to specify lengths or other values. You have a much faster build cycle without the need to generate XML files. The biggest advantage is that you can access useful information such as a not null annotation or length at run time. In addition to the annotations illustrated in Listing 2, you can specify validation constraints. Some of the included constraints available are:

  • @Max(value = 100)
  • @Min(value = 0)
  • @Past
  • @Future
  • @Email

When appropriate, these annotations will cause check constraints to be generated with the DDL. (Obviously, @Future is not an appropriate case.) You can also create custom constraint annotations as needed.

Validation and application layers

Writing validation code can be a tedious, time-consuming process. Often, lead developers will forgo addressing validation in a given layer to save time, but it is debatable whether or not the drawbacks of cutting corners in this area are offset by the time savings. If the time investment needed to create and maintain validation across all application layers can be greatly reduced, the debate swings toward having validation in more layers. Suppose you have an application that lets a user create an account with a username, password, and credit card number. The application components into which you would ideally like to incorporate validation are as follows:

  • View: Validation through JavaScript is desirable to avoid server round trips, providing a better user experience. Users can disable JavaScript, so while this level of validation is good to have, it's not reliable. Simple validations of required fields are a must.
  • Controller: Validation must be processed in the server-side logic. Code at this layer can handle validations in a manner appropriate for the specific use case. For example, when adding a new user, the controller may check to see if the specified username already exists before proceeding.
  • Service: Relatively complex business logic validation is often best placed into the service layer. For example, once you have a credit card object that appears to be valid, you should verify the card information with your credit card processing service.
  • DAO: By the time data reaches this layer, it really should be valid. Even so, it would be beneficial to perform a quick check to make sure that required fields are not null and that values fall into specified ranges or adhere to specified formats -- for instance, an e-mail address field should contain a valid e-mail address. It's better to catch a problem here than to cause avoidable SQLExceptions.
  • DBMS: This is a common place to find validation being ignored. Even if the application you're building is the only client of the database today, other clients may be added in the future. If the application has bugs (and most do), invalid data may reach the database. In this event, if you are lucky, you will find the invalid data and need to figure out if and how it can be cleaned up.
  • Model: An ideal place for validations that do not require access to outside services or knowledge of the persistent data. For example, your business logic may dictate that users provide at least one form of contact information, either a phone number or an e-mail address; you can use model layer validation to make sure that they do.

A typical approach to validation is to use Commons Validator for simple validations and write additional validations in the controller. Commons Validator has the benefit of generating JavaScript to process validations in the view. But Commons Validator does have its drawbacks: it can only handle simple validations and it stores the validation definition in an XML file. Commons Validator was designed to be used with Struts and does not provide an easy way to reuse the validation declarations across application layers.

When planning your validation strategy, choosing to simply handle errors as they occur is not sufficient. A good design also aims to prevent errors by generating a friendly user interface. Taking a proactive approach to validation can greatly enhance a user's perception of an application. Unfortunately, Commons Validator fails to offer support for this. Suppose you want your HTML to set the maxlength attribute of text fields to match the validation or place a percent sign (%) after text fields meant to collect percentage values. Typically, that information is hard-coded into HTML documents. If you decide to change your name property to support 75 characters instead of 60, in how many places will you need to make changes? In many applications, you will need to:

  • Update the DDL to increase the database column length (via HibernateDoclet, hbm.xml, or Hibernate Annotations).
  • Update the Commons Validator XML file to increase the max to 75.
  • Update all HTML forms related to this field to change the maxlength attribute.

A better approach is to use Hibernate Validator. Validation definitions are added to the model layer through annotations, with support for processing the validations included. If you choose to leverage all of Hibernate, the validator helps provide validation in the DAO and DBMS layers as well. In the code samples that follow, you will take this a step further by using reflection and JSP 2.0 tag files, leveraging the annotations to dynamically generate code for the view layer. This will remove the practice of hard-coding business logic in the view.

Hibernate DAO implementations use the validation annotations as well, if you want them to. All you need to do is specify Hibernate event-based validation in the hibernate.cfg.xml file.

Saturday, July 21, 2007

Introducing Hibernate

Hibernate is a full-featured, open source OR mapping framework for the Java platform. In many ways Hibernate is similar to EJB CMP CMR (container-managed-persistence/container-managed-relationships), and JDO (Java Data Objects). Unlike JDO, Hibernate focuses entirely on OR mapping for relational databases, and includes more features than most commercial products. Most EJB CMP CMR solutions use code generation to implement persistence code, while JDO uses bytecode decoration. Conversely, Hibernate uses reflection and runtime bytecode generation, making it nearly transparent to end users. (Earlier implementations of Hibernate used reflection only, which aids in debugging, and current versions retain this option.)       

Porting Hibernate-based apps

If your application must run on many RDBMS systems, Hibernate-based applications port almost effortlessly from IBM DB2, MySQL, PostgreSQL, Sybase, Oracle, HypersonicSQL, and many more. I even recently worked on an application port from MySQL to Firebird, which isn't all that well supported by Hibernate, and the port was effortless. See Resources for a case study of a switch between Postgres and MySQL.

Hibernate allows you to model inheritance (several ways); association (one-to-one or one-to-many, containment, and aggregation); and composition. I'll cover several examples of each type of relationship in this article.

Hibernate provides a query language called Hibernate Query Language (HQL), which is similar to JDO's JDOQL and EJB's EJB QL; although it is closer to the former. But Hibernate doesn't stop there: it also allows you to perform direct SQL queries and/or use object criteria to compose criteria easily at runtime. I'll use only HQL in the examples for this article.

Unlike EJB CMP CMR and like JDO, Hibernate can work inside of or outside of a J2EE container, which is a boon for those of us doing TDD and agile development.

Introducing Spring

The first time AOP expert Nicholas Lesiecki explained AOP to me, I didn't understand a word he was saying; and I felt much the same the first time I considered the possibility of using IOC containers. The conceptual basis of each technology alone is a lot to digest, and the myriad of new acronyms applied to each one doesn't help -- particularly given that many of them are variations on stuff we already use.

Like many technologies, these two are much easier to understand in practice than in theory. Having done my own research on AOP and IOC container implementations (namely, XWork, PicoContainer, and Spring), I've found that these technologies help me gain functionality without adding code-based dependencies on multiple frameworks. They'll both be a part of my development projects going forward.

In a nutshell, AOP allows developers to create non-behavioral concerns, called crosscutting concerns, and insert them in their application code. With AOP, common services like logging, persistence, transactions, and the like can be factored into aspects and applied to domain objects without complicating the object model of the domain objects. 

Developing with a new framework without unit testing is like walking on a new trapeze wire without a net: sure you could do it, but you're going to bleed. I prefer to develop with a net, and for me that net is TDD. Before DbUnit came along, testing code that was dependent on a database could be a little tough. DbUnit is an extension of JUnit that provides a framework for unit tests dependent on a database. I used DbUnit to write the test code for the example classes in this article. While not present in the article, the DbUnit code is part of the article source code (see Resources). Or for an introduction to DbUnit, see "Control your test-environment with DbUnit and Anthill" (developerWorks, April 2004) by Philippe Girolami.

IOC allows me to create an application context where I can construct objects, and then pass to those objects their collaborating objects. As the word inversion implies, IOC is like JNDI turned inside out. Instead of using a tangle of abstract factories, service locators, singletons, and straight construction, each object is constructed with its collaborating objects. Thus, the container manages the collaborators.

Spring is both an AOP framework and an IOC container. I believe it was Grady Booch who said the great thing about objects is that they can be replaced; and the great thing about Spring is that it helps you replace them. With Spring, you simply inject dependencies (collaborating objects) using JavaBeans properties and configuration files. Then it's easy enough to switch out collaborating objects with a similar interface when you need to.

Spring provides an excellent on-ramp to both IOC containers and AOP. As such, you don't need to be familiar with AOP in order to follow the examples in this article. All you need to know is that you'll be using AOP to declaratively add transactional support to your example application, much the same way that you would use EJB technology. See Resource to learn more about Spring.

Friday, July 20, 2007

Java Testing Tool froglogic Squish Supports New Eclipse Europa

Squish for Java is a professional functional GUI and regression testing tool enabling the creation and execution of automated GUI tests for Java SWT/RCP and AWT/Swing applications.

Squish, and all tests created with it, are completely cross-platform and work on Windows, Linux/Unix, Mac OS X and embedded Linux.

Support for testing Eclipse 3.3 RCP applications has now been completed and will be released to the public as of the next Squish maintenance release 3.2.2. A pre-release is available to customers upon request.

"Following our cross-platform and cross-technology philosophy it is important for us to stay up to date with latest developments in the Java market. We decided to react quickly and implemented support for the improved version 3.3 of the Eclipse framework", said Koos Vriezen, froglogic's Java team lead.

Squish offers a versatile testing framework for GUI applications with a choice of popular test scripting languages (Python, JavaScript, Tcl, TSL and Perl) extended by test-specific functions, open interfaces, add-ons, integrations into test management tools, a powerful IDE
aiding the creation and debugging of tests and a set of command line tools facilitating fully automated test runs.

If you are interested in evaluating or purchasing Squish for Java or any other edition of Squish, please contact squish at froglogic dot com or visit www.froglogic.com/squish.

Squish also supports automated testing of applications based on GUI technologies such as Trolltech's Qt and Qtopia, Web/DOM/HTML/AJAX, Tk, Four J's Genero and others.

Talk with GoogleTalk inside of Eclipse

ECF is a diverse collection of communication and collaboration tools. One of these is support for talking to any XMPPS (Jabber) server. Given that the popular Google Talk system uses XMPPS, we can easily configure Google Talk to run inside an Eclipse view.

Firstly, this assumes you're using Eclipse Europa. Although ECF existed prior to Europa, the update sites weren't built in and the UIs might be slightly different.

Secondly, it assumes that you have ECF installed. If not, go to Help -> Software Updates -> Find and Install, and then drill into the 'Search for new features to install'. The Europa Discovery Site (http://download.eclipse.org/releases/europa) should be selected, and after hitting Finish, the Eclipse Communication Framework will be shown in the Communications category. You only need the Core feature, although you can download the examples to play around with as well if you want. I suggest that you restart Eclipse once you've installed it.

So, having got an Eclipse Europa install, how do we get it ready to use GoogleTalk? Well, there's a 'Communications' perspective which you can switch to, but very little idea of how you'd create a new account. It turns out that there's a little button in the action bar ( ) which will let you add new accounts. If you click on the arrow to the right of it, a drop-down menu will appear with IRC, MSN, XMPP, XMPPS and BitTorrent.

Select the XMPPS one (the encrypted version of XMPP) and you'll get window asking for your username and password. This is the same one that you sign in to Google Talk; it's usually something like Joe dot Bloggs at gmail dot com. If you find you have problems, sometimes you can also sign in with Joe dot Bloggs at talk dot google dot com, but you generally won't need to do this.

Once you click on 'Finish', you'll get a Contacts view, and from there, all of your Google contacts will be displayed. You can even set your status using the drop-down menu item at the top of the view, for example, to note that you're away or fixing a particularly vexing problem and that you'll be back soon.

As I'm sure Scott will point out, ECF doesn't just handle Google Talk. There are a number of other supported protocols, including an IRC chat on irc://irc.freenode.net/#eclipse if your firewalls will allow it. But there's lots more to ECF; that's a subject for another day.

Happy talking!