Category Archives: Java

Frameworks in Architecture Definition

There are lot of frameworks which disappeared with time, also there are few frameworks which have changed the way applications are getting developed. These successful frameworks have contributed to give a new look to Java itself. There are many reasons behind continued success of different frameworks available in market. These days Java application development involves considerable use of proven frameworks. Below are some benefits we get by using these frameworks.

* Readymade components to speed up the development
* Developer community support to help
* As all are OpenSource, Everything comes free of cost
* Successfully Proven technology assuring success of project

Now, we will explore the architecture trends arising due to wide usage of these ready frameworks in application development, assuming readers to be aware of different popular Java based open source frameworks e.g. Struts, Spring, Hibernate etc.

Layered Architectures:

Architecture definition involves identifying tiers and further different layers to separate each unit responsibility. Definitely the driver is business requirement, which makes us to separate presentation from business and business from data access. Let us take following simple example where we have three tiers – web tier, business tier and database tier. Each tier has clear responsibility.

Presentation tier also called as web tier handles presentation part along with navigation from one screen to other. Additional features like managing user session, caching information etc. will be additional expected features in presentation tier.

Business tier encapsulates complete business logic. Business validations, processing, calculations etc. gets handled in this layer. Transaction management, security etc. are the enterprise features expected in this layer.

Database tier involves implementation of database interaction and processing of retrieved or to be persisted data. Database session management, transaction propagation etc. are the features expected here.

When we select ready frameworks to implement each of these tiers, different layers in a tier are identified by the selected framework already. We can customize these layer but up to certain extend only.

Predefined Layers with different Frameworks:

The word framework broadly means ready components and skeleton on which we can construct a larger program. Some amount of flexibility is available to choose better alternatives suitable to the application. To explore it further, let us take each tier and try to identify layer alternatives according when we use different framework.

Presentation Layer:

As we move from one framework to other, the type of objects we use go on changing. Here Action, Controller, and Page Components encapsulate navigation logic. This means that when we use these frameworks we have to have a layer that contains everything related to navigation. If you remember the days of servlet, everything related to navigation along with request data extraction and population in data object used to be inside servlet code. Now we get the request data populated in mapped pojos, and what we need to do is identify next navigation point in these action/controller/pagecomponent classes. Framework takes care of rest of the things. Thus we have limited options in this tier with usage of one of these frameworks.

Business Layer:

This layer contains everything related to business. An application might require exposing the business functions as a service, and we decide to use Spring Webservice for this purpose. This implementation will require following simple layers.

Here the first layer just deals with webservice request –response-fault handling including marshaling and un-marshaling, while the second class contains actual business function implementation. These two layer can be clearly indentified in with usage of Spring Webservices.

Database Layer:

In this layer, we take example of hibernate framework which accesses oracle database. We require a Dao (data access object) layer that offers create, read, update and delete (CRUD) operations on data objects (which map to database entities directly).

From the above discussion, we can conclude that each (OpenSource) framework has it’s own requirement of layers, when we select the framework we also identify these layers directly in our architecture. We can leverage little flexibility provided by the framework to customize it according to our needs.

Framework Usage View:

With above preliminary discussion, We can clearly see a need of representation that shows how different frameworks in different tiers interact with each other. Not only interaction but interaction in following context –

* Thread management
* Transaction management
* Data transformation (e.g. if you are using struts then action form is required but it can not be directly passed to hibernate as it requires conversion into object that represents database table.)
* Exception management support
* Individual framework benefits and constraints

This list can be longer depending on application and frameworks considered.

EclEmma – Java Code Coverage for Eclipse

EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. Internally it is based on the great EMMA Java code coverage tool, trying to adopt EMMA’s philosophy for the Eclipse workbench:

Fast develop/test cycle: Launches from within the workbench like JUnit test runs can directly be analyzed for code coverage.
Rich coverage analysis: Coverage results are immediately summarized and highlighted in the Java source code editors.
Non-invasive: EclEmma does not require modifying your projects or performing any other setup.

The Eclipse integration has its focus on supporting the individual developer in an highly interactive way.

Features

Launching

EclEmma adds a so called launch mode to the Eclipse workbench. It is called Coverage mode and works exactly like the existing Run and Debug modes. The Coverage launch mode can be activated from the Run menu or the workbench’s toolbar:

Simply launch your applications or unit tests in the Coverage mode to collect coverage information. Currently the following launch types are supported:

* Local Java application
* Eclipse/RCP application
* Equinox OSGi framework
* JUnit test
* TestNG test
* JUnit plug-in test
* JUnit RAP test
* SWTBot test

Analysis

After your application or unit test has terminated code coverage information is automatically available in the Eclipse workbench:

* Coverage overview: The Coverage view lists coverage summaries for your Java projects, allowing drill-down to method level.
* Source highlighting: The result of a coverage session is also directly visible in the Java source editors. A customizable color code highlights fully, partly and not covered lines. This works for your own source code as well as for source attached to instrumented external libraries.

Additional features support analysis for your test coverage:

* Different counters: Select whether instructions, lines, basic blocks, methods or loaded types should be summarized.
* Multiple coverage sessions: Switching between coverage data from multiple sessions is possible.
* Merge Sessions: If multiple different test runs should be considered for analysis coverage sessions can easily be merged.

Import/Export

While EclEmma is primarily designed for test runs and analysis within the Eclipse workbench, it provides some import/export features.

* Coverage data import: A wizard allows to import *.ec coverage data files from external launches.
* Coverage report export: Coverage data can be exported as a *.ec file or in XML or HTML format.

JavaFX 1.3 Released, Improves User Experiences

This release represents an important upgrade to the product and delivers a range of performance and functional improvements, including:

* New and enhanced support for UI controls, CSS skinning, and programmatic layout
* Performance improvements in the JavaFX Runtime
* New NetBeans IDE 6.9 Beta with improved editing and an updated JavaFX Composer plug-in
* New features and enhanced performance in JavaFX Production Suite
* A native JavaFX font family called Amble
* Support for the development of TV applications, including a new TV emulator
* Availability of the mobile emulator on the Mac platform

It might be hard to believe that JavaFX has only been in the market for less than one and a half years, it certainly is for us! In that time, we’ve built out the foundation for mobile with a deployment ready runtime, delivered a library of UI controls to make it substantially easier to build out consistent user interfaces, and were able to entice developers to download over 400,000 copies of our tools by our 1.2 release. We’ve released a beta of the JavaFX Composer to provide visual-editing for form-based UIs with an exceptionally positive response and seen the community rally around the platform with projects like JFXtras, numerous blogs, and over a dozen books. We’ve also been very excited to see companies like the Vancouver Organizing Committee for the 2010 Olympic and Paralympic Winter Games adopting the technology for commercial products and services, and we’ve got another well-known customer that we’re excited to start talking to you about shortly!

But lets get back to the JavaFX 1.3 release. As we began working with some of these high-profile customers, we found they were really pushing the limits of JavaFX. Since our 1.2 release we’ve spent a lot of time carefully evaluating our performance goals to meet the needs of these customers and have heavily optimized in the following areas:

* Bind performance: 2-3x faster
* Applet start-up time: 20% faster (with Java SE 6u18+)
* Text Rendering: 5-10x faster (frames per second/FPS)
* Highly complex animations: up to 10x faster (FPS)
* Memory usage: 20-33% reduction (real-world apps, w/ Java SE 6u18+)
* UI Controls: 50% faster, 33%-50% less memory (typical)

Lets take a quick look at a few of these. Binding has often been described as one of the more powerful features in JavaFX, but many developers found they had to use it sparingly due to performance considerations. In JavaFX 1.3 we’ve implemented substantial improvements in the way JavaFX handles binding and have seen tremendous payoffs, in particular with applications that make heavy usage of this feature.

Start-up time is another area where we’ve made substantial improvements. First, it’s important to understand that we measure start-up time in two ways. We measure both cold-start (the first time a user loads an applet, includes download and initialization) and warm-start (subsequent launches of the applet). Cold-start is critical, because it’s the user’s first impression and it’s also where we’ve achieved the most improvements with 1.3. To improve start-up time, we implemented a number of optimizations throughout the stack, including the JRE and the JavaFX runtime. Basic applications running on systems with a recent version of the JRE (Java SE 6u18+) launch 20% faster and complex applications start nearly twice as fast! Obviously your mileage will vary depending on the specifics of your application.

Animation performance has been another area of focus in JavaFX 1.3. In one of our more extreme benchmarks, we applied animations to 900 objects simultaneously. In JavaFX 1.2 this would have resulted in a paltry 6 FPS. With JavaFX 1.3 we are now seeing an impressive 67 FPS – that’s over 10x faster! Unless you are using a ton of objects in your application you probably won’t see this kind of performance gain but we’ve effectively removed animations as a performance bottleneck so developers can use them much more freely in their applications. A similar benchmark with 500 animated objects managed to deliver a 5x improvement.

A key area of focus in JavaFX 1.2 was to deliver UI controls to make it easier for developers to build great looking user interfaces. This effort was very well received by the community and has actually become one of the most requested areas for continued improvement! To this end, UI Controls have continued to be a major area of focus for us with JavaFX 1.3. With 1.3, we have added and/or substantially upgraded 9 controls and have released previews for an 8 additional controls for developers to begin experimenting with in their applications. In addition, we have rewritten all of the existing UI controls to take full advantage of the new CSS support in JavaFX, making them simpler, more powerful and highly customizable. Our UI controls improvements have also yielded substantial performance gains, in particular with applications that make heavy usage of UI controls such as enterprise-class applications. While applications that use complex UI controls (such as ListView & TreeView) will be 150% faster, and consume up to 50% less memory, we achieved substantially better performance with more complex applications. For example, a 1.3 application with 200 controls uses 50-80% less memory, starts nearly twice as quickly, and runs 50% faster (comparisons are with 1.2). For developers who might have used UI controls sparingly in the past and/or avoided using JavaFX for applications that required a substantial number of UI controls, JavaFX 1.3 really opens the door to a range of new use-cases.

Genuitec introduces MyEclipse IDE for the Spring Framework

Genuitec will introduce on Tuesday a version of its MyEclipse IDE for use with the popular open source Spring Framework for Java development, sans the backing of the major developer of the framework itself, SpringSource.

Also in the Spring vein Tuesday, SpringSource is discontinuing dm Server, a Java application server based on modular OSGi technology, as a commercial product. SpringSource is looking to farm out continued development of dm Server to the Eclipse Foundation.

Genuitec, for its part, is offering its $199-per-year MyEclipse for Spring IDE at the end of this month. Based on a collaboration between Genuitec and Skyway Software, MyEclipse for Spring offers MyEclipse functionality as well as scaffolding technology allowing access to editors for rapid creation of applications, Genuitec said. Application scaffolding generates large portions of the application using best practices, said Todd Williams, Genuitec vice president of technology.

The MVC (Model View Controller) scaffolding generates Spring MVC CRUD (Create Read Update Delete) applications from database tables, plain old Java objects and Java Persistence Architecture entities.

Currently, Spring developers can use the Genuitec MyEclipse Pro IDE for code-level development. “What’s new [with the Spring-centered IDE] is a level above [Pro] that enables you to create entire tiers or connected tiers of the application,” Williams said.

Spring technologies supported include “everything from their database persistence layer through their services layer through [Spring] Web Flow,” which is Spring GUI technology, Williams said.

But Adam Fitzgerald, director of developer relations at SpringSource, was dismissive of the Genuitec product. He instead endorsed the free SpringSource Tool Suite as a mechanism for building Spring applications.

“I would recommend going with the tool that comes [from] the company that created Spring,” Fitzgerald said. “[The suite] really is the most cutting-edge way to build Spring apps.”

Also featured in the MyEclipse for Spring are project bootstrapping, for building Spring configuration files and adding Java libraries and Web resources. Enhanced development editors offeri simplified configuration of services, controllers and Spring Web Flow.

Meanwhile, SpringSource Tuesday will detail plans to hand off development of dm Server to Eclipse, but with SpringSource still participating in development and offering support subscriptions. The project under Eclipse jurisdiction would be called Virgo; the formal switchover to Eclipse is expected to take a couple of months, Fitzgerald said.

In explaining the move, Fitzgerald cited difficulties in getting mass adoption of OSGi at the enterprise level, even though OSGi offers greater control of system dependencies and modularization of application components.

“Certainly, dm Server was not as successfully adopted [as] something like [Apache] Tomcat or [SpringSource] tc Server,” but there have been successful use cases, said Fitzgerald.

The move to Eclipse means project hosting, home pages, forums, and downloads will be at Eclipse.org. Licensing will change from a largely GPL license to Eclipse Public License.

The combination of the license change and community hosting at Eclipse.org opens the code base to a much broader set of users and developers, according to SpringSource. “We think this is an opportunity for opening up dm Server to really push OSGi to the forefront of enterprise Java development and make it more than just a tool for cutting edge companies,” Fitzgerald said.

SpringSource Tuesday is unveiling dm Server 2.0; the planned 2.1 follow-up release would be developed by Eclipse. The Eclipse nickname for the project is Virgo.

Version 2.0 of dm Server features changes to how modules are provisioned; modules can be built across local and remote repositories. SpringSource debuted dm Server in Fall 2008.

Top Ten Errors Java Programmers do

Here’s my top ten list of errors that we all seem to make at one time or another, how to spot them, and how to fix them.

10. Accessing non-static member variables from static methods (such as main)

Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static – meaning that we don’t need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-

MyApplication.main ( command_line_args );

This means, however, that there isn’t an instance of MyApplication – it doesn’t have any member variables to access! Take for example the following application, which will generate a compiler error message.

public class StaticDemo
{
public String my_member_variable = “somedata”;

public static void main (String args[])
{
// Access a non-static member from static method
System.out.println (”This generates a compiler error” +
my_member_variable );

}
}

If you want to access its member variables from a non-static method (like main), you must create an instance of the object. Here’s a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.

public class NonStaticDemo
{
public String my_member_variable = “somedata”;

public static void main (String args[])
{
NonStaticDemo demo = new NonStaticDemo();

// Access member variable of demo
System.out.println (”This WON’T generate an error” +
demo.my_member_variable );
}
}

9. Mistyping the name of a method when overriding

Overriding allows programmers to replace a method’s implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you’ll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you’re no longer overriding a method – you’re creating an entirely new method, but with the same parameter and return type.

public class MyWindowListener extends WindowAdapter {
// This should be WindowClosed
public void WindowClose(WindowEvent e) {
// Exit when user closes window
System.exit(0);

}
});

Compilers won’t pick up on this one, and the problem can be quite frustrating to detect. In the past, I’ve looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn’t being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn’t being called, then it’s likely you’ve mistyped the name.

8. Comparison assignment ( = rather than == )

This is an easy error to make. If you’re used other languages before, such as Pascal, you’ll realize just how poor a choice this was by the language’s designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.

Fortunately, even if you don’t spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : “Can’t convert xxx to boolean”, where xxx is a Java type that you’re assigning instead of comparing.

7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here’s the correct way to compare two strings.

String abc = “abc”; String def = “def”;

// Bad way
if ( (abc + def) == “abcdef” )
{
……
}

// Good way
if ( (abc + def).equals(”abcdef”) )
{
…..
}

6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you’re passing by value, and when you’re passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the “real” variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes – a String is actually an object, not a primitive data type. So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object’s member variables will be permanent – which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

5. Writing blank exception handlers

I know it’s very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven’t written any error messages, it becomes almost impossible to find out the cause of the error. Even the simplest exception handler can be of benefit. For example, put a try { .. } catch Exception around your code, to catch ANY type of exception, and print out the message. You don’t need to write a custom handler for every exception (though this is still good programming practice). Don’t ever leave it blank, or you won’t know what’s happening.

For example

public static void main(String args[])
{
try {
// Your code goes here..
}
catch (Exception e)
{
System.out.println (”Err – ” + e );
}
}

4. Forgetting that Java is zero-indexed

If you’ve come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element’s index is actually 0. Confused? Let’s look at a quick example.

// Create an array of three strings
String[] strArray = new String[3];

// First element’s index is actually 0
strArray[0] = “First string”;

// Second element’s index is actually 1

strArray[1] = “Second string”;

// Final element’s index is actually 2
strArray[2] = “Third and final string”;

In this example, we have an array of three strings, but to access elements of the array we actually subtract one. Now, if we were to try and access strArray[3], we’d be accessing the fourth element. This will case an ArrayOutOfBoundsException to be thrown – the most obvious sign of forgetting the zero-indexing rule.

Other areas where zero-indexing can get you into trouble is with strings. Suppose you wanted to get a character at a particular offset within a string. Using the String.charAt(int) function you can look this information up – but under Java, the String class is also zero-indexed. That means than the first character is at offset 0, and second at offset 1. You can run into some very frustrating problems unless you are aware of this – particularly if you write applications with heavy string processing. You can be working on the wrong character, and also throw exceptions at run-time. Just like the ArrayOutOfBoundsException, there is a string equivalent. Accessing beyond the bounds of a String will cause a StringIndexOutOfBoundsException to be thrown, as demonstrated by this example.

public class StrDemo
{
public static void main (String args[])
{
String abc = “abc”;

System.out.println (”Char at offset 0 : ” + abc.charAt(0) );

System.out.println (”Char at offset 1 : ” + abc.charAt(1) );
System.out.println (”Char at offset 2 : ” + abc.charAt(2) );

// This line should throw a StringIndexOutOfBoundsException

System.out.println (”Char at offset 3 : ” + abc.charAt(3) );
}
}

Note too, that zero-indexing doesn’t just apply to arrays, or to Strings. Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application.

import java.util.Date;
import java.util.Calendar;

public class ZeroIndexedDate
{
public static void main (String args[])
{
// Get today’s date

Date today = new Date();

// Print return value of getMonth
System.out.println (”Date.getMonth() returns : ” +
today.getMonth());

// Get today’s date using a Calendar

Calendar rightNow = Calendar.getInstance();

// Print return value of get ( Calendar.MONTH )
System.out.println (”Calendar.get (month) returns : ” +
rightNow.get ( Calendar.MONTH ));

}
}

Zero-indexing is only a problem if you don’t realize that its occurring. If you think you’re running into a problem, always consult your API documentation.

3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy’s law holding, the probability) that two threads will access or modify the same data at the same time. Don’t be fooled into thinking that such problems won’t occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{
count = amount;
}

public synchronized int getCount()

{
return count;
}
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It’s so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don’t spot the lack of capitalization.

While there’s no silver bullet for detecting this error, you can easily train yourself to make less of them. There’s a very simple trick you can learn :-

* all methods and member variables in the Java API begin with lowercase letters
* all methods and member variables use capitalization where a new word begins e.g – getDoubleValue()

If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you’ll make. It may take a while, but it can save some serious head scratching in the future.
(drum roll)
And the number one error that Java programmers make !!!!!

1. Null pointers!

Null pointers are one of the most common errors that Java programmers make. Compilers can’t check this one for you – it will only surface at runtime, and if you don’t discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven’t initialized an object, or you haven’t checked the return value of a function.

Many functions return null to indicate an error condition – but unless you check your return values, you’ll never know what’s happening. Since the cause is an error condition, normal testing may not pick it up – which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];

int index = 0;

while ( (index < args.length) && ( index < 3 ) )

{
list[index++] = args[index];
}

// Check all the parameters
for (int i = 0; i < list.length; i++)
{
if (list[i].equals “-help”)
{
// ………
}
else
if (list[i].equals “-cp”)

{
// ………
}
// else …..
}
}

This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you’ll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won’t. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Top 10 tools for java development

As a java developer, we always trying to get someone else to do little jobs for us.  This is a list of tools (and possibly frameworks) that we have found most helpful in any java development.

  1. Eclipse (http://www.eclipse.org) – everyone should know what eclipse is by now. The reason we include it here is mostly due to the refactoring support is immensely helpful.
  2. Ant (http://ant.apache.org/) – again, everyone should know this tool by now. Ant is a fantastic build tool, but allows you to do much more with all of the extension support. We have seen some very cool things done with ant, ivy and a few custom tasks.
  3. JUnit (http://junit.org/) – people should know this framework, but many people still don’t subscribe to the automated unit testing model. I find automated unit tests a great way to ensure you haven’t broke anything mainly because I regularly break my own tests.
  4. Tomcat (http://tomcat.apache.org/) – Tomcat is obviously more useful if you are doing web development in java. Duh. However, if you do any of that and have tried configuring something like WebSphere, you can understand why I include it.
  5. Sitemesh (http://www.opensymphony.com/sitemesh/) – Sitemesh is one of the simplest web presentation frameworks I have seen. It can be seen as a basic template engine, but quite often that is all that you need. The difficulty with most web frameworks is that they try to be all things to all people. Sitemesh just wants to put a nice configurable template around your content. The idea of “do one thing and do it well” comes to mind.
  6. Spring (http://www.springframework.org/) – Spring is one of the “web” frameworks that tries to be all things to all people. However, it doesn’t do a bad job. If you are involved with a large project, Spring gives you some nice functionality out of the box without having to go the coding standards route.
  7. Ivy (http://ant.apache.org/ivy/) – Well, some things have changed in Ivy-land. It is an ant subproject now and soon to be moving to the ant site. This might be a good thing. Ivy is a dependency management tool that can be used with ant. If you have more than one small project, you are likely to need dependency management. I like it because I am not required to move to Maven which I have not had much success with.
  8. Luntbuild (http://luntbuild.javaforge.com/) – Luntbuild is an open source GUI build management tool. So, you already have your ant builds and they can be integrated with luntbuild. The bonus with luntbuild is that you can have separate development, qa and production configurations for the build. There is also a professional version called quickbuild (http://www.pmease.com/) that comes with support and some additional features.
  9. Cobertura (http://cobertura.sourceforge.net/) – This is my favorite code coverage tool, mainly because it works and it is free. Code coverage is a good metric to have because it will quickly show you where you have less tests. You will never hit 100% coverage (and you shouldn’t), but it is a good benchmark to look at, especially if you get some defect density numbers from your code as well.
  10. Xerces (http://xerces.apache.org/) – Is there any other XML parsing library out there?

If we have missed your favorite tool, let me know and I will try to look into it. I am always on the lookout for new tools that can improve productivity.

Tools For Unit Testing Java Web Applications

There are a lot of ways to do unit tests, but sometimes unit testing becomes difficult. This could be because we need to test a Struts action or we do not want the unit tests to hit the database. So, the question is what tools can we use for testing java web applications? This is not meant as a complete and thorough overview, just some of the tools we know of or have looked into at some time. In many cases, you will find that the testing code is very repetitive, so we may end up building frameworks on top of these frameworks. I am sure I missed something or maybe even your favorite, so just leave me a comment.

Basic Java Testing – JUnit and TestNG are the most popular tools for basic java unit testing. JUnit typically has a small advantage as it has been around longer and is included with most packages of Eclipse. However, I do not think one is really better than the other, they are just different.

Mock Objects – EasyMock and jMock are popular mock objects frameworks. Sometimes you have to simulate the way another system works, and mock objects are perfect for this. You can even create your own mock object, but the frameworks make it easy to avoid extra code.

Database Interaction – DBUnit is really the only decent framework I have seen. It allows you to insert data before the test is run and cleans up after the test is complete. However, capturing the appropriate data for a test is not simple for anything but the most trivial applications.

User Interface Testing – UI testing is notoriously difficult and many applications skip it entirely. If you are testing your generated html, you will want to look at the following tools and determine which best suits your needs. This is a special case, as there is no “one true way” to test the user interface. These are all free tools as I am a fan of keeping things as cheap as possible if the tools are good enough.

* Selenium – Maybe the most complete package of the bunch and supports testing in IE, FireFox and Safari. Your unit tests are written in java, so you just need to learn the API. They also have interesting server options where you can run your tests across servers. You can even record tests using a FireFox add-on.
* Canoo WebTest – This is another framework that can record tests with a FireFox add-on. The tests for WebTest are typically written in xml files. This gives you the option to build a library of fragments of functionality to include in various tests. You can also write your tests in Groovy or use the Java API directly. These can also be run directly from within Ant.
* Watij – This is a port of the popular Ruby testing framework, Watir. The tests are written in Java using their API. They also include BeanShell so that you can interactively test your code. This is a really interesting option if you are not sure what a unit test should look like initially.
* JWebUnit – This is more of a meta-framework, where it can build upon HtmlUnit or Selenium. HtmlUnit is fairly good by itself, but sometimes a framework is just too low-level for some people or people find that they keep doing the same things and decide to build upon the framework. There is one problem with JWebUnit, the documentation is very sparse, so the learning curve ciould be problematic.
* Cactus – This is another meta-framework, but this is from Apache. It is meant as a wrapper for testing an entire application from basic java testing, servlet testing and down to the user interface testing. Due to this meta concept, the documentation can be a bit vague. However, I have heard good things from those people that spent the time to learn more. Disappointingly, I have not had the time to dive into it much.

There are a lot of other tools out there as well. FitNesse is very popular, but it takes a very distinct approach to how unit tests are built. For Struts applications, there is a framework called StrutsTestCase that is immensely helpful as well. For a big list of testing and related software, take a look at XProgramming.com. They list testing frameworks for almost every language. Lastly, it is always a good idea to know how well your software is tested. This is not a question of whether all of your tests pass, but how much of the code is actually tested. My favorite test code coverage tool is Cobertura. It is fairly simple to use and the reports are generated in a similar manner to how JUnit generates reports.

So, if you know of a good free java testing tool, drop me a note in the comments. Sometimes a good tool may not be getting enough publicity or I may not have had time to look at it. In any case, keep testing until you have good test coverage. And remember the testing mantra, “Red, Green, Refactor”