Showing posts with label download. Show all posts
Showing posts with label download. Show all posts

Friday, August 29, 2008

Load jar files and Java classes dynamically

In this post I present a way to load jar files and Java classes dynamically from java code. It can be very useful, if you want to create module, for example.

Design Pattern
The solution build up from three part, the
Loader - loads and uses the jar files and Java class dynamically,
Communication interface(s) - defines the interface, what can be used to communicate the program and the dynamic library,
Dynamic libraries - the Loader loads and uses this libraries through the communication interface(s).

The loader, the communication interface(s) and the dynamic libraries must be separated in different projects, because
  • Loader imports the communication interface(s)
  • Dynamic libraries imports the communication interface(s)
  • Loader can't know anything about the Dynamic libraries
  • Dynamic libraries can't know anything about the Loader



Sample application
As usually, I made a sample application, what can help to you to understand my idea. The sample application is very similar now. The main program can be invocated with two parameter, the first is the name of the jar file to load, the second is the name of the class to load. The application loads the given jar file and class and say hello in two different language, depend on, which jar file is loaded.

Creating the communication interface(s)
There is only one communication interface, what defines only one simple method:



Creating a dynamic library
The sample dynamic library is as simple as the communication interface:


Creating the Loader
Sample application has a main class, what processes the program arguments:


and a class, where the codes are separated, that load the jar file and class dynamically:


Downloads
You can download sample projects here as NetBeans project.

Saturday, August 2, 2008

Spring Framework - First Steps

This post teaches you some useful basic information and function of Spring framework. Writing XML configuration files, wiring beans, loading XMLs, using ApplicationContext. Creating, publishing and listening events are discussed in this post too.

TaskbarNotifier example application
The functions above are represented through an example application. This application has a GUI frame, where we can create animals, given the genus, the name and the color:


and when user click to the Create and notify button, then the created animal properties are showed in a tooltip message on taskbar:


Step 1: Creating the project
Create a new java application project with your favorite IDE and add the following files from Spring to the application classpath:
  • spring.jar
  • spring-core.jar
  • spring-context.jar
  • commons-logging.jar
  • log4j-1.2.xy.jar
Step 2: Creating the model
Now we create the model, the objects, on our application operates. We have a simple JavaBean, named Animal with three simple properties:
  • genus - genus of the animal
  • name - name of the animal
  • color - color of the animal
Our Animal JavaBean:


Step 3: Creating the service interfaces
Services are very important in Spring. They implement the business logic, operate with the application data. To create a service, first we create an interface with methods, that the service will implement (it's function will be discussed in another post).

Our example application has two service interfaces:
  • AnimalService - Creates Animal instance from its properties.
  • TaskbarService - Shows the taskbar icon, displays tooltip message on taskbar and closes the taskbar icon.
Our AnimalService interface:

Our TaskbarService interface:

Step 4: Implementing the service interfaces
Implementing the service interface is a simple interface implementation, its complexity depends on the complexity of the business logic.
Our application has two service interfsce implementations:
  • AnimalServiceImp
  • TaskbarServiceImp

AnimalServiceImp source code:


TaskbarServiceImp source code:

Step 5: Creating and publishing events
Events can be very useful when we want to inform other parts of our application, something interesting happened.

To create an event, we have to extend the org.springframework.context.ApplicationEvent abstract class and create a constructor, what call a super() with a parameter. This parameter is usually the object, what is behind to the published event.

If we have an event instance then we can publish it through an ApplicationContext instance, using the publishEvent() method, like this (where context is an ApplicationContext instance):
context.publishEvent(new TaskbarNotificationEvent(animal)); //This code segment is from AnimalServiceImp class

Working of events is represented by the following chart:


Our application have only one publishable event:
  • TaskbarNotificationEvent - This event is published when a new Animal instance created.
TaskbarNotificationEvent Source code:


Step 6 : Creating the Listener class
As I discussed above, ApplicationListeners are waiting for published events and they (of course we, programmers) decide, is the actual event important to this listener or not. If it is then the listener can run some event-specific code, otherwise it should do nothing (but can, if it wants).

To create an own listener, we need implement the org.springframework.context.ApplicationListener interface. This interface has a single method:
public void onApplicationEvent(ApplicationEvent event);


Through the event parameter we can access the actual published event. With the instanceof operator we can decide the type of the event.

The example application has only one Listener:
  • TaskbarNotifier.
TaskbarNotifier Source Code:


Step 7: Creating GUI
There's a simple thing, that I discuss in this step:
I write the windowClosing event to my Frame:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
/**
* Close the application, using the AppController.exit() method.
* The defaultCloseOperation of form is set to EXIT_ON_CLOSE.
*/
AppController.exit();
}


I did it because i want to run some code before the application is closed (remove the taskbar icon for example).

Our application has only one frame:
  • MainFrame.
MainFrame Source Code:


Step 8: The XML configuration file
As I said, we can use XML configuration files to define beans, wire beans, set configurations. In a separated post I will write only about the XML configuration file, now see only the required information to create our sample application.

Our sample application's XML configuration file looks like this:



XML Scheme
To use the XML file with Spring framework, we have to start our XML file like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
These lines mean our XML file version is 1.0 and the encoding of the file is UTF-8. It's recommended keep these settings.

The next two lines is a DTD import. It can be used to check the validation of our XML file.

Root element
All XML file have to be a root element. If we create XML configuration file to Spring framework then the root element must be:
<beans>
...
</beans>
All bean definition, configuration code and everything have to be between the beans open and close tag.

Simple bean definition
The most easiest way to define a bean is the following:
<bean id="animalService" class="example.animal.AnimalServiceImp" />
This definition means:
  • create an instance of class example.animal.AnimalServiceImp
  • assign the animalService identification to the created instance
  • if we refering the created instance through the animalService identification, we always access to the same object instance (singleton) it can be changed, it will be discussed later
Wiring beans, dependency injection
We define a bean to access an example.taskbar.TaskbarServiceImp instance:
<bean id="taskbarService" class="example.taskbar.TaskbarServiceImp" />

And now, we define an other bean, what is a little more complex, because we set the taskbarService properties of the created bean:
<bean id="taskbarNotifier" class="example.taskbar.TaskbarNotifier">
<property name="taskbarService">
<ref bean="taskbarService" />
</property>
</bean>

This definition means:
  • create an instance of class example.taskbar.TaskbarNotifier
  • assign the taskbarNotifier identification to the created instance
  • if we refering the created instance through the taskbarNotifier identification, we always access to the same object instance (singleton) it can be changed, it will be discussed later
  • get the example.taskbar.TaskbarServiceImp instance with taskbarService identification and set the created bean's taskbarService property through its setter method to this taskbarService object
This way to creating and connecting beans can be little strange, but it is very very useful, there are so many thing, that we can't make without this solution.

Summary
If your read this post, you can
  • add the required files to use Spring framework
  • create service interfaces
  • implement service interfaces
  • create and publish events
  • listen and handle events
Using XML configuration files can be strange first, but I will create a post only about it. Understand using these files is very important to understand Spring framework itself.

Downloads
You can download example code here as NetBeans project.

Sunday, July 13, 2008

SCJP Exam - Objective 1.3 Part II

Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.

There are three things, what you should know about array:
  1. declaring array
  2. constructing array
  3. initializing array

Declaring arrays
Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier.

Declaring array of primitives
Declaration of an array of primitives looks like this:
<primitive type>[] <identifier>;

for example:
int[] integer_array;

There is another way to declare arrays (like in language C):
<primitive type> <identifier>[];

for example:
int anotherArray[];
Declaring array of objects
Declaration of array of objects:
<classname>[] <identifier>;

for example:
String[] stringArray;
Array of object can be declared as in language C too.

Declaring multidimensional arrays
Java let you to declare multidimensional arrays. Multidimensional arrays are arrays of arrays.
A two dimensional array declaration:
String[][] twoDimensionalArray;

The
String[][] threeDimensionalArray[];

declaration is interesting, but legal.

Constructing arrays
Constructing an array means creating the array object on the heap. To create an array object, Java must know how much space to allocate on the heap, so user must specify the size of the array at creation time. The size of the array is the number of elements the array will hold.

Examples
int[] intArray; //Declare an one-dimensional array
intArray = new int[3]; //Construct an int array to hold 3 int value
long longArray = new long[1]; //Declare and construct a long array with one element


Constructing multidimensional array
Remember, multidimensional arrays are simply arrays of arrays. It means, elements of multidimensional arrays are arrays.
The
int[][] array = new int[2][];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 2. When we initialize the array then we can put int array as elements with different size into the array.
The
int otherArray = new int[3][2];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 3 and declare and construct three one-dimension array with length 2 and put them into the array.

Initializing arrays
Initializing an array means putting things (primitives, object references) into it:
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
int b[] = new int[2];
b[0] = 8;
b[1] = 9;
int[][] c;
c = new int[2][];
c[0] = a;
c[1] =b;
String[] s = new String[3];
s[0] = "hello";
s[1] = null; //null can be use as string element
s[2] = new String("World");

Notice, array indexes begin with 0 and go to size-1. If we try refer to an index that not exist (for example a negative number, or a number greater then size-1) then ArrayIndexOutOfBoundsException trowed.

Declaring, constructing and initializing arrays
It's possible to declare, construct and initialize array in the same time:
int[] a = { 5, 6, 7 };
String lenovo = new String("Lenovo");
String[] computerProducers = { "Dell", lenovo, "HP", "Apple" };

Anonymous array creation
Anonymous array creation can be used to construct and initialize an array, and then assign the array to a previously declared array reference variable:
String[] operatingSystems;
operatingSystems = new String[] { "Windows XP", "Windows Vista", "OpenSuSE 10.3" };

Multidimensional array creation
Multidimensional array creation looks like this:
int[][] array = { { 1, 2, 3 }, { 10, 11 }, { 0 } };

Declare, initialize and uses arrays, enums, objects as static, instance and local variables
Example code:

You can download source code here.

Thursday, July 10, 2008

Spring Framework - Introduction

Spring is an open-source framework, created by Rod Johnson. It was created to address the complexity of enterprise application development. Spring makes it possible to use JavaBeans to achieve things that were previously only possible with EJBs. However, Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.

Web: http://www.springframework.org/

Lightweight — Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs in at just over 1 MB. And the processing overhead required by Spring is negligible. What’s more, Spring is non intrusive: objects in a Spring-enabled application typically have no dependencies on Spring specific classes.

Inversion of control — Spring promotes loose coupling through a technique known as inversion of control (IoC). When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of IoC as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.

Aspect-oriented — Spring comes with rich support for aspect-oriented programming
that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support.

Container — Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. You can configure how your each of your beans should be created—either create one single instance of your bean or produce a new instance every time one is needed based on a configurable prototype—and how they should be associated with each other. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large and cumbersome to work with.

Framework — Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to developer.

Starting with Spring Framework
Downloading required files
You can download the latest release of Spring framework from this link. Select the spring-framework-2.x.z-with-dependencies.zip file, that contains the base files and the files to use Spring modules.

Unpacking file
Unpack the downloaded zip file to a directory. The directory structure, that is created looks like this:
The [lib] is the most important directory, the JAR files to Spring extensions are here.

Creating the first Spring application
Our sample application will have a service interface and implementation, what writes the Hello World to the console.

Required JAR files
To build and run our first application using Spring framework, we must add the following JAR files to the classpath:
  • spring.jar
  • spring-core.jar
  • spring-context.jar
  • commons-logging.jar
  • log4j-1.2.xy.jar
You can see, Spring is really lightweight.

Creating the Service interface
I don't discuss this step, this is a simple interface declaration.

Source code:

Implementing the interface
This is an easy step too, a simple interface implementation, I hope everyone realizes it.

Source code:

Creating configuration XML file
This is the first step, where we see something new: the XML configuration file. These files are the "heart of Spring". Here are the bean definitions, configuration data, I discuss it later in detail.

In brief, we create 3 instance of GreetingServiceImp with identification
  • greetingService
  • inheritedGreetingService
  • wrongGreetingService
GreetingServiceImp has two user-defined property:
  • greetingMessage
  • name
The
<bean id="greetingService" class="spring.example.helloworld.GreetingServiceImp">
<property name="greetingMessage">
<value>Hello</value>
</property>
<property name="name">
<value>World</value>
</property>
</bean>
bean definition means:
  1. create a spring.example.helloworld.GreetingServiceImp instance,
  2. set the property greetingMessage to "Hello",
  3. set the property name to "World",
  4. assign the greetingService identification to the instance.

XML file:

Running the code
The running code gets the three GreetingServiceImp instance from the ApplicationContext and calls the sayHello() methods.
The
ApplicationContext context = new ClassPathXmlApplicationContext("greeting.xml");

line create an ApplicationContext instance. Through this context we can access the beans defined in greeting.xml file, like this:
GreetingService greeting = (GreetingService) context.getBean("greetingService");

Source code:

Downloads
You can download this sample application as NetBeans project with dependencies here.

Tuesday, July 8, 2008

Applying Model Viewing Controller to Java Web Applications Using JSP and Servlet

Model viewing controller is an architectural pattern. We can use to separate the user interface and the business logic. By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.


It isn't goal of this post to explain the using JSP and Servlet technologies. Maybe in another post I will do it.


Participants of the Model Viewing Controller Design Pattern
(based on Wikipedia)

model - the domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.
viewing - renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.
controller - processes and responds to events, typically user actions, and may invoke changes on the model.

A simple diagram depicting the relationship
between the Model, View, and Controller.


Model Viewing Controller in action
  1. The user interacts with the user interface.
  2. A controller handles the input event from the user interface, often via a registered handler or callback.
  3. The controller notifies the model of the user action, possibly resulting in a change in the model's state.
  4. A view uses the model (indirectly) to generate an appropriate user interface. The view gets its own data from the model. The model has no direct knowledge of the view.
  5. The user interface waits for further user interactions, which begins the cycle anew.



Model Viewing Controller in action


Participants of the Model Viewing Controller Design Pattern - Java Web Application Using JSP and Servlet

model
- a web application usually operates on database. There are several ways to access database from web application (JDBC, Hibernate, Toplink...).
viewing - Java Server Pages (JSP) can be used as user interface. With JSP technologies we can generate contents to web browsers, mobile phones, XML files.
controller - Servlets was developed to control the web application and access to the database, what the application use.

Model Viewing Controller in action - Java Web Application Using JSP and Servlet

In the first step, the user visits a web portal with his web browser:


Example web application

The viewed content is generated by a viewer, a JSP file:

By clicking Greeting! button, the given name will be sent to the controller Servlet. In this time the form's content is sent to the specified controller (action property, in this case greeting.controller). The property method specify the type of request (GET or POST).

The controller, in this case the GreetingServlet get the http request.
The servlets have two entry point, depends on it get a http GET or http POST query:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
So depend on the type of request, the suitable method is invocated, the specified codes begin to run.

In my example the servlet looks like this:

The servlet processes the data and the processing is forwarded to the result.jsp, where greetings message will be showed:

Downloads
You can download example code here as NetBeans project.

Sunday, June 29, 2008

SCJP Exam - Objective 1.1

Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

Java Source File
Sample Java source file:



You can download source code here.
  1. If the class is part of a package, the package statement must be the first in the source code file.
  2. The import statements must be after the package statement (if there is one) and must be before the class declaration.
  3. There can be only one public class per source code file.
  4. If there is a public class in a file, the name of the file must match the name of the public class.
  5. A source file can have more than one nonpublic class.
  6. Files with no public classes can have a name that does not match any of the classes in the file.
Static import

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;
or:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

Class declaration
Class declaration looks like this:
<Class modifier> class <ClassName> {
//...
}
Modifiers
Access modifiers
  1. A class can be declared as public and default access.
  2. A class never can be declared as private or protected, except the inner classes.
Non-access modifiers
  1. abstract
  2. final
  3. strictfp

Non-access modifier: abstract
An abstract class can never be instantiated. If you try it, you get Compilation fails. The abstract classes are to extend them.

If we have some classes with the same methods, but some method implementation are different then abstract class is a perfect choice:
Make an abstract class, write the methods, that will be same in the subclasses.
Mark the methods, that will have different implementations as abstract. Abstract methods end in a semicolon rather than curly braces.

Example for abstract class and its concrete classes:

You can download source code here.


Non-access modifier: final
When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend a final class, and any attempts to do so will give you a compiler error.

Many classes in the Java core libraries are final. For example, the string class. So notice, you never ever can extend the String class.

Example for final class and the Compilation fails when try to extend the class, marked final:

You can download source code here.


Non-access modifier: strictfp
Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way.

Notice,
  • an abstract class never ever can be instantiated
  • abstract class can have constructor and it can be called from subclasses constructors trough super()
  • a final class never ever can be extended
  • a class never ever can be marked as both abstract and final
Declaring nested classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
//...
class NestedClass {
//...
}
}
Type of nested classes:
  1. static nested class
  2. inner (non-static) class
  3. local class
  4. anonymous class
Static nested class
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Inner class
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
//...
class InnerClass {
//...
}
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Local inner class
You can declare an inner class within the body of a method. Such a class is known as a local inner class:
class OuterClass {
public void someMethod() {
class InnerClass {
//..
}
}
}
Notice,
  1. a local inner class can be instantiated only within the method where the inner class is defined
  2. a local inner class can not access to the method's local variables
  3. a local inner class can access to the method's local variables, marked as final

Anonymous class
Anonymous classes extends an exists class or implements an interface, with creating a new class without name:
class Tree {
public void grow() {
//Some tree specific code
}
}

interface Door {
void closeDoor();
}

public class MyClass {
public void doStuff() {
Tree oak = new Tree {
public void grow() {
//Some oakvspecific code
}
}

Door door = new Door {
public void closeDoor() {
//Close door method
}
}
}
}



Interface declaration

Interface declaration looks like this:
<Class modifier> interface <InterfaceName> {
//...
}
Notice,
  • all interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract
  • all variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables

  • interface methods must not be static

  • because interface methods are abstract, they cannot be marked final, strictfp, or native

  • an interface can extend one or more other interfaces

  • an interface cannot extend anything but another interface

  • an interface cannot implement another interface or class

  • an interface must be declared with the keyword interface

  • interface types can be used polymorphically

Puzzle 1
Given the following code:
interface Tree {
void grow();
}

public class Oak implements Tree {
void grow() {
//Some oak specific code here...
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because methods in interface declaration are implicitly public and the accession of grow() method in Oak class is default.

Puzzle 2
Given the following code:
interface MyInterface {
int x = 67;
}

class MyClass implements MyInterface {
public void setter() {
x = 100;
}
}
What is the result?
The result is: the code does not compile, it causes Compilation fails, because variables, declared in interfaces are implicitly final and static, and you can not assign a new value to a final variable.

Declaring Enums
Using enums can help reduce the bugs in your code.

Example for declaring enumerations:

You can download source code here.

Friday, June 27, 2008

Pop-up Window with Return Value

Trick
In this post a trick is presented: possibility to return object from a pop-up dialog.

It can be useful to
  • select and return an element of list from a pop-up dialog
  • create a new object in a pop-up dialog and return it
  • edit an object in a pop-up dialog and return it
Participants
Caller - the place, where the pop-up window is opened and the returned data is processed.
Dialog - this is the pop-up window, what produces the return object.

Step 1: Creating the dialog
Create a GUI window, what extends the javax.swing.JDialog class, like this:



My sample dialog creates and returns a String instance from a TextField.

Step 2: Extend the dialog code
First add a new class member to the created dialog class:

private <ReturnObjectClass> returnValue;

where the <ReturnObjectClass> is the class of the object, what our pop-up window returns, in my case:

private String returnValue;

Now write the actions to the buttons.
Cancel button close the window and return null:

returnValue =null;
dispose();

Return button close the window and return the new String:

returnValue = jTextField1.getText();
dispose();

At least construct the method, what return the created object:

public String getValue() {
this.setVisible(true);
return returnValue;
}

Step 3: Creating the caller
Create a class, named Main, and put the following code:

public static void main(String[] args) {
String s = new GetStringDialog(null, true).getValue();
System.out.println("Dialog returned with: " + s);
}

After you run this program, the pop-up dialog is showed and after clicking the Return button the typed string is written to the console.

Downloads
You can download sample code here as NetBeans project.

Monday, June 23, 2008

Mediator Design Patter

I present this post an useful adaptation of Mediator Design Pattern. We need often create GUI forms and of course we want to process the information given by users.

Participants of Mediator Design Patter
(based on Wikipedia)

Mediator - defines the interface for communication between Colleague objects.

ConcreteMediator - implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication.

ConcreteColleague - communicates with other Colleagues through its Mediator



Step 1: Create the Mediator interface
In the 1rst step we create the mediator interface:

1. public interface Mediator {
2. void setData( HashMap<String, Object> data );
3. HashMap<String, Object> getData();
4. }

Import the required classes and our Mediator is done.
Object will communicate over this interface with each other.


Step 2: Create the form
We create a simple GUI frame with two JTextField and two JButton, like this:



Step 3: Create the ConcreteMediator
To create the ConcreteMediator, implement the Mediator interface with our GUI Frame.
Change the
public class MediatorExample extends javax.swing.JFrame {

line to
public class MediatorExample extends javax.swing.JFrame imlements Mediator {

and implement the required methods, declared in Mediator interface:
public void setData(HashMap data) {
textfield_info1.setText((String) data.get("info1"));
textfield_info2.setText((String) data.get("info2"));
}
and
public HashMap getData() {
HashMap data = new HashMap();
data.put("info1", textfield_info1.getText());
data.put("info2", textfield_info2.getText());
return data;
}

Import the required classes and our ConcreteMediator is done (textfield_info1 and textfield_info2 are the name of two JTextField instance variable).


Step 4: Create the ConcreteColleague
In our example the ConcreteColleague has two function:
it can open a new Frame and fill it with initial data throught the Mediator interface
it can process form data throught Mediator interface.
My code:
public class ImportantDataProcessor {

public void showImportantDataDialog() {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("info1", "This information is very important!");
data.put("info2", "And Top Secret!");

MediatorExample frame = new MediatorExample();
frame.setData(data);
frame.setVisible(true);

}

public void processImportantData(Mediator mediator) {
HashMap<String,Object> data = mediator.getData();

String info1 = (String) data.get("info1");
String info2 = (String) data.get("info2");

JOptionPane.showMessageDialog(null, info1 + "\n" + info2, "Important Information",
JOptionPane.INFORMATION_MESSAGE);
}
}

Import the required classes and our ConcreteColleague is done .


Step 5: Process the form
Now we write the onClick() events of the two buttons.
Exit button will close the application:
this.dispose();
and the Process... button will start the form processing:
new ImportantDataProcessor().processImportantData(this);
The "this" word refer to the GUI frame itself, what implements the Mediator interface.


Step 6: Start the application
Create a class, named Main, and put the following code:
public static void main(String[] args) {
new ImportantDataProcessor().showImportantDataDialog();
}


Downloads
You can download sample code here as NetBeans project.