Java MD5 example

18Sep2010 In: Core Java

Java MD5 Overview

MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value, specified in RFC 1321, MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994). MD5 has been employed in a wide variety of security applications, and is also worldwide used to check the integrity of files.

MD5 is a perfect solution for security thinking. The Java developers usually may take over or code MD5 encryption, the MD5 encryption is complicated, for self-coding it’s hard to implement. Java standard edition has MD5 support built in. in package, class MessageDigest supports functionality of a message digest algorithm, such as MD5 or SHA. Read the rest of this entry »

Jframe tutorial and example

17Sep2010 In: Swing

Jframe is a very basics component in java swing package, it  is a must learning if you any Java GUI applications, this tutorial and example is for this, it covers the JFrame introduction, usage and demonstrate how to create simple Jframe programs. Read the rest of this entry »

Junit and Ant

12Sep2010 In: Junit

Junit and Ant Overview

Junit and Ant are respectively Java standard unit testing framework and command-line tool, most of the time, we need to integrate them together for a project, in this tutorial I cover how to use Junit in ant task. To get started I assume you understand the basic knowledge and usages of Junit and Ant, otherwise please you may get first chance to read the manual (Junit tutorial and example).
First off, make sure you have a Java installed, then download ant library from (, uncompress the downloaded file into a directory, add ANT/BIN directory to ANT_HOME env variable.

We start writing Junit test case, for simplicity, we create a test case as following, it is a always passed case.

 * This class is used to test runing junit in ant task.
 * Date: 2010-9-12
 * Time: 21:39:18
import junit.framework.*;
public class JunitExample extends Assert {
    public void testMethod() {
        int a = 10;
        assertEquals(a, 10);

We need to run this case from Ant command line rather than a IDE, so create a ANT build xml as showed below, there have several Ant targets, they take account in appropriate responsibility in this build procedure, target “init” prepares the all initiated parameters, target ‘compile’ depends on ‘init’ and is used to compile Java source codes.

<project name="JunitAntExample" default="test" basedir=".">
        This class is used to test runing junit in ant task.

    <property environment="env"/>
    <target name="init">
       <property name="main.src" value="src"/>
       <property name="build.dir" value="build"/>
       <property name="build.reports" value="build/report"/>
       <property name="build.classes" value="${build.dir}/classes"/>
       <property name="tests.lib" value="test"/>

       <property name="reports.dir" value="reports"/>

       <path id="test.cp">
       <filelist dir="${tests.lib}">
       <file name="junit.jar"/>

    <target name="compile" depends="init">
       <mkdir dir="${build.classes}"/>
       <javac destdir="${build.classes}" debug="true" optimize="true" 
deprecation="false" failonerror="true">
       <src path="${main.src}"/>
       <path refid="test.cp"/>

    <target name="test" depends="compile">
       <mkdir dir="${build.reports}"/>
       <junit fork="yes" forkmode="once" haltonfailure="no" showoutput="no" printsummary="yes">
         <formatter type="xml"/>
            <pathelement location="${build.classes}"/>
            <path refid="test.cp"/>
         <batchtest todir="${build.reports}">
            <fileset dir="src">
               <include name=""/>
       <junitreport todir="${build.reports}">
         <fileset dir="${build.reports}">
         <include name="TEST-*.xml"/>
         <report format="frames" todir="${reports.dir}/junit_reports"/>


You may change junit library path to fit your environment, here is explanation and official document of attributes of Ant Target ‘Junit’:

fork Run the tests in a separate VM.
forkmode Controls how many Java Virtual Machines get created if you want to fork some tests. Possible values are “perTest” (the default), “perBatch” and “once”. “once” creates only a single Java VM for all tests while “perTest” creates a new VM for each TestCase class. “perBatch” creates a VM for each nested <batchtest> and one collecting all nested <test>s. Note that only tests with the same settings of filtertrace, haltonerror, haltonfailure, errorproperty and failureproperty can share a VM, so even if you set forkmode to “once”, Ant may have to create more than a single Java VM. This attribute is ignored for tests that don’t get forked into a new Java VM. since Ant 1.6.2
showoutput Send any output generated by tests to Ant’s logging system as well as to the formatters. By default only the formatters receive the output.
printsummary Print one-line statistics for each testcase. Can take the values on, off, and withOutAndErr. withOutAndErr is the same as on but also includes the output of the test as written to System.out and System.err.
batchtest A series of test class which need to run

The default target is set to ‘test’ in build XML, so from commend line, use command “ant” without target specified or “ant test” to run to run this task, this is output:

Buildfile: build.xml



    [junit] Running JunitExample
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.1 sec
[junitreport] Processing E:\apache\JunitAntExample\build\report\TESTS-TestSuites.xml to C:\Users\ADMINI~1\AppData\Local\Temp\
[junitreport] Loading stylesheet jar:file:/D:/Program%20Files/apache-ant-1.7.1/lib/ant-junit.jar!/org/apache/tools/ant/taskde
[junitreport] Transform time: 529ms
[junitreport] Deleting: C:\Users\ADMINI~1\AppData\Local\Temp\null1758654992


If plus ‘verbose’ on the end(“ant test -verbose”), more details are available:

E:\apache\JunitAntExample>ant test -verbose
Apache Ant version 1.7.1 compiled on June 27 2008
Buildfile: build.xml
Detected Java version: 1.5 in: C:\Program Files\Java\jdk1.5.0_22\jre
Detected OS: Windows Vista
parsing buildfile E:\apache\JunitAntExample\build.xml with URI = file:/E:/apache/JunitAntExample/build.xml
Project base dir set to: E:\apache\JunitAntExample
[] Could not load definitions from resource org/apache/tools/ant/antlib.xml. It could not be found
 [property] Loading Environment env.
Build sequence for target(s) `test' is [init, compile, test]
Complete build sequence is [init, compile, test, ]


    [mkdir] Skipping E:\apache\JunitAntExample\build\classes because it already exists.
    [javac] omitted as E:\apache\JunitAntExample\build\classes\JunitExample.class is up to date.

    [mkdir] Skipping E:\apache\JunitAntExample\build\report because it already exists.
    [junit] Implicitly adding D:\Program Files\apache-ant-1.7.1\lib\ant-launcher.jar;D:\Program Files\apache-ant-1.7.1\lib\an
t.jar;D:\Program Files\apache-ant-1.7.1\lib\ant-junit.jar to CLASSPATH
    [junit] Executing 'C:\Program Files\Java\jdk1.5.0_22\jre\bin\java.exe' with arguments:
    [junit] '-classpath'
    [junit] 'E:\apache\JunitAntExample\build\classes;E:\apache\JunitAntExample\test\junit.jar;E:\apache\JunitAntExample;C:\Pr
ogram Files\Java\jdk1.5.0_22\lib;D:\Program Files\apache-ant-1.7.1\lib\ant-launcher.jar;D:\Program Files\apache-ant-1.7.1\lib
\ant.jar;D:\Program Files\apache-ant-1.7.1\lib\ant-junit.jar'
    [junit] ''
    [junit] 'JunitExample'
    [junit] 'filtertrace=true'
    [junit] 'haltOnError=false'
    [junit] 'haltOnFailure=false'
    [junit] ''
    [junit] 'showoutput=false'
    [junit] 'outputtoformatters=true'
    [junit] 'logtestlistenerevents=true'
    [junit] ',E:\apache\JunitAntExample\build\r
    [junit] 'crashfile=E:\apache\JunitAntExample\'
    [junit] 'propsfile=E:\apache\JunitAntExample\'
    [junit] The ' characters around the executable and arguments are
    [junit] not part of the command.
    [junit] Running JunitExample
    [junit] junit.framework.TestListener: tests to run: 1
    [junit] junit.framework.TestListener: startTest(testMethod)
    [junit] junit.framework.TestListener: endTest(testMethod)
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.102 sec
[junitreport] Parsing file: 'E:\apache\JunitAntExample\build\report\TEST-JunitExample.xml'
[junitreport] Using class
[junitreport] Processing E:\apache\JunitAntExample\build\report\TESTS-TestSuites.xml to C:\Users\ADMINI~1\AppData\Local\Temp\
[junitreport] Loading stylesheet jar:file:/D:/Program%20Files/apache-ant-1.7.1/lib/ant-junit.jar!/org/apache/tools/ant/taskde
[junitreport] Transform time: 510ms

When reviewing the build file, You may ready noticed that the particular two lines <formatter type="xml"/> and <junitreport todir="${build.reports}"> exist in XML, this tells that reports are outputted to ${build.reports} and format is XML. Alternative, you can also ask for generating HTML reports.

  • The xml formatter element nested in the junit element produces raw data XML files.
  • The following junit report task generates a summary XML file named TESTS-TestSuites.xml
  • The report element nested in the junitreport task generates the final HTML and css files
  • The combination of the formatter plus the following batchtest task generates the pretty HTML reports.

I finally attached the screen shot of Junit html report, it is easy to quickly finger out whats cases pass/fail, for failures, stack track is provided.

Junit Tutorial and Example

8Sep2010 In: Junit

Junit is a most famous open source unit testing and regression testing framework in java, which was originally written by Erich Gamma and Kent Beck, it has became an industry standard framework which developers write repeatable tests and do white-box testing. Read the rest of this entry »

JUnit Tutorial – Suite Test

6Sep2010 In: Junit

In previous tutorial we introduced how to run a single test case, however, most of the time we have to bunch same kind of cases along, this is what “suite test” stands for in Junit, a suite is a collection of test cases that are intended to be used to test a software program to show that it has some specified set of behaviors. In Junit, annotation @RunWith and @Suite are used to run a suite test. Read the rest of this entry »

Junit Time and Parameterized Test

25Aug2010 In: Junit

One: Junit Time test

The “Junit Time Test” means if an unit test takes longer than the specified number of milliseconds to run, the test will be terminated and marked as failed. This is an extremely useful case to test these time-consuming operations, for instance: you connect a database to retrieve items, if it has no return after taking longer than one minute, you probably want to terminate this testcase and mark it as failed. Read the rest of this entry »

Junit Ignore Test

25Aug2010 In: Junit

We designed a lot of some cases which test software behavior, however, some of them might be exceptions which run into problem or even not ready to test, we’d like to ignore or skip these cases but keep no-changes to existing code base. Annotation @ignore in JUnit 4 allows a test to be differed until it is ready (or the feature is).

Read the rest of this entry »

Junit Tutorial – Expected Exception Test

25Aug2010 In: Junit

Junit doesn’t only intend to ensure that code is working as expected and validate that this is still the case after code changes, it’s also capable for testing method which expects to throw desired exception.

Two ways are available in Junit to test expected exception.

1. Catch the exception and assert success, if this exception was not thrown then assert fail

public void testIndexOutOfBoundsException() {
  try {
    System.out.println("test :: IndexOutOfBoundsException");
    List list = new ArrayList();
    fail("There should throw IndexOutOfBoundsException");
  } catch (IndexOutOfBoundsException e) {
    //There should do something validate  excpetion
    assertEquals(e.getMessage(),  "Index: 1, Size: 0");

Read the rest of this entry »

Junit Tutorial – Basic Usage and Annotation

25Aug2010 In: Junit

This tutorial introduces how to write testcase with Junit 4 and explains basic annotations supported in junit 4.
Read the rest of this entry »

Junit 4 Tutorial and Example – Get Starting

21Aug2010 In: Junit

Junit 4 Tutorial and example

  1. If you use Idea or Eclipse, The Junit IDE plug-in is normally included as a part of the IDE distribution.
  2. If do not using Idea or Eclipse, you can still use Junit as a standalone testing tool by downloading it from(

Creating a Junit Test case

  1. Open the IDE, create a test project, if needed, please import the Junit library to your current project dependency libraries.
  2. Create a test class named SimpleTest and extends junit.framework.TestCase in the test project. In generic, the best practice is to define the test class name to start with ‘test’ and plus class name which need to be tested. (in case you use Junit4, it is no longer necessary to extend junit.framework.TestCase)
  3. Write a test method and assert desired results. If you use the Junit 3, you have to conventional define string ‘test’ as the prefix of test method, but in junit 4 or later, you can use annotation @Test to declare it, then Junit engine will explain it as a test method. Read the rest of this entry »