Wednesday, December 29, 2004

Patterns 3 : Behavioral patterns

Chain of Responsibility
The Chain of Responsibility pattern allows a number of classes to attempt to handle a request, without any of them knowing about the capabilities of the other classes. It provides a loose coupling between these classes; the only common link is the request that is passed between them. The request is passed along until one of the classes can handle it.

Applicability
We use the Chain of Responsibility when
· You have more than one handler that can handle a request and there is no way to know which handler to use. The handler must be determined automatically by the chain.
· You want to issue a request to one of several objects without specifying which one explicitly.
· You want to be able to modify the set of objects dynamically that can handle requests.

A Chain or a Tree?
Of course, a Chain of Responsibility does not have to be linear. The Smalltalk Companion suggests that it is more generally a tree structure with a number of specific entry points all pointing upward to the most general node.

Another way of handling a tree-like structure is to have a single entry point that branches to the specific button, menu or other widget types, and then “un-branches” as above to more general help cases. There is little reason for that complexity -- you could align the classes into a single chain, starting at the bottom, and going left to right and up a row at a time until the entire system had been traversed.

Consequences of the Chain of Responsibility
1. The main purpose for this pattern, like a number of others, is to reduce coupling between objects. An object only needs to know how to forward the request to other objects.
2. This approach also gives you added flexibility in distributing responsibilities between objects. Any object can satisfy some or all of the requests, and you can change both the chain and the responsibilities at run time.
3. An advantage is that there may not be any object that can handle the request, however, the last object in the chain may simply discard any requests it can’t handle.
4. Finally, since Java can not provide multiple inheritance, the basic Chain class needs to be an interface rather than an abstract class, so that the individual objects can inherit from another useful hierarchy, as we did here by deriving them all from JPanel. This disadvantage of this approach is that you often have to implement the linking, sending and forwarding code in each module separately.

Command pattern
The Chain of Responsibility forwards requests along a chain of classes, but the Command pattern forwards a request only to a specific module. It encloses a request for a specific action inside an object and gives it a known public interface. It lets you give the client the ability to make requests without knowing anything about the actual action that will be performed, and allows you to change that action without affecting the client program in any way.

One important purpose of the Command pattern is to keep the program and user interface objects completely separate from the actions that they initiate. In other words, these program objects should be completely separate from each other and should not have to know how other objects work. The user interface receives a command and tells a Command object to carry out whatever duties it has been instructed to do. The UI does not and should not need to know what tasks will be executed.

The Command object can also be used when you need to tell the program to execute the command when the resources are available rather than immediately. In such cases, you are queuing commands to be executed later. Finally, you can use Command objects to remember operations so that you can support Undo requests.

Consequences of the Command Pattern
The main disadvantage of the Command pattern is a proliferation of little classes that either clutters up the main class if they are inner or clutters up the program namespace if they are outer classes.
Now even in the case where we put all of our actionPerformed events in a single basket, we usually call little private methods to carry out the actual function. It turns out that these private methods are just about as long as our little inner classes, so there is frequently little difference in complexity between inner and outer class approaches.

Anonymous Inner Classes
We can reduce the clutter of our name space by creating unnamed inner classes by declaring an instance of a class on the spot where we need it. For example, we could create our Red button and the class for manipulating the background all at once

btnRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.setBackground(Color.red);
}
} );

This is not very readable, however, and does not really improve the number of run-time classes since the compiler generates a class file even for these unnamed classes.

In fact, there is very little difference in the compiled code size among these various methods, once you create classes in any form at all.

Byte code size of Command class implementations
Program type Byte code size
No command classes 1719
Named inner classes 4450
Unnamed inner classes 3683
External classes 3838

Providing Undo
Another of the main reasons for using Command design patterns is that they provide a convenient way to store and execute an Undo function. Each command object can remember what it just did and restore that state when requested to do so if the computational and memory requirements are not too overwhelming.

Interpreter pattern
Some programs benefit from having a language to describe operations they can perform. The Interpreter pattern generally describes defining a grammar for that language and using that grammar to interpret statements in that language.

Motivation
When a program presents a number of different, but somewhat similar cases it can deal with, it can be advantageous to use a simple language to describe these cases and then have the program interpret that language. Such cases can be as simple as the sort of Macro language recording facilities a number of office suite programs provide, or as complex as Visual Basic for
Applications (VBA). VBA is not only included in Microsoft Office products, but can be embedded in any number of third party products quite simply.

One of the problems we must deal with is how to recognize when a language can be helpful. The Macro language recorder simply records menu and keystroke operations for later playback and just barely qualifies as a language; it may not actually have a written form or grammar. Languages such as VBA, on the other hand, are quite complex, but are far beyond the
capabilities of the individual application developer. Further, embedding commercial languages such as VBA, Java or SmallTalk usually require substantial licensing fees, which make them less attractive to all but the largest developers.

Applicability
As the SmallTalk Companion notes, recognizing cases where an Interpreter can be helpful is much of the problem, and programmers without formal language/compiler training frequently overlook this approach. There are not large numbers of such cases, but there are two general places where languages are applicable:

1. When the program must parse an algebraic string. This case is fairly obvious. The program is asked to carry out its operations based on a computation where the user enters an equation of some sort. This frequently occurs in mathematical-graphics programs, where the program renders a curve or surface based on any equation it can evaluate.
Programs like Mathematica and graph drawing packages such as Origin work in this way.

2. When the program must produce varying kinds of output. This case is a little less obvious, but far more useful. Consider a program that can display columns of data in any order and sort them in various ways. These programs are frequently referred to as Report Generators, and
while the underlying data may be stored in a relational database, the user interface to the report program is usually much simpler then the SQL language which the database uses. In fact, in some cases, the simple report language may be interpreted by the report program and translated into SQL.

Consequences of the Interpreter Pattern
Whenever you introduce an interpreter into a program, you need to provide a simple way for the program user to enter commands in that language. It can be as simple as the Macro record button we noted earlier, or it can be an editable text field like the one in the program above.

However, introducing a language and its accompanying grammar also requires fairly extensive error checking for misspelled terms or misplaced grammatical elements. This can easily consume a great deal of programming effort unless some template code is available for implementing this checking. Further, effective methods for notifying the users of these errors are not easy to design and implement.

In the Interpreter example above, the only error handling is that keywords that are not recognized are not converted to ParseObjects and pushed onto the stack. Thus, nothing will happen, because the resulting stack sequence probably cannot be parsed successfully, or if it can, the item represented by the misspelled keyword will not be included.

You can also consider generating a language automatically from a user interface of radio and command buttons and list boxes. While it may seem that having such an interface obviates the necessity for a language at all, the same requirements of sequence and computation still apply. When you have to have a way to specify the order of sequential operations, a language is a good way to do so, even if the language is generated from the user interface.

The Interpreter pattern has the advantage that you can extend or revise the grammar fairly easily one you have built the general parsing and reduction tools. You can also add new verbs or variables quite easily once the foundation is constructed.

In the simple parsing scheme we show in the Parser class above, there are only 6 cases to consider, and they are shown as a series of simple if statements. If you have many more than that, Design Patterns suggests that you create a class for each one of them. This again makes language extension easier, but has the disadvantage of proliferating lots of similar little classes. Finally, as the syntax of the grammar becomes more complex, you run the risk of creating a hard to maintain program. While interpreters are not all that common in solving general programming problems, the Iterator pattern we take up next is one of the most common ones you’ll be using.

Iterator pattern
The Iterator is one of the simplest and most frequently used of the design patterns. The Iterator pattern allows you to move through a list or collection of data using a standard interface without having to know the details of the internal representations of that data. In addition you can also define special iterators that perform some special processing and return only specified elements of the data collection.

Mediator pattern
When a program is made up of a number of classes, the logic and computation is divided logically among these classes. However, as more of these isolated classes are developed in a program, the problem of communication between these classes become more complex. The more each class needs to know about the methods of another class, the more tangled the class structure can become. This makes the program harder to read and harder to maintain. Further, it can become difficult to change the program, since any change may affect code in several other classes. The Mediator pattern addresses this problem by promoting looser coupling between these classes. Mediators accomplish this by being the only class that has detailed knowledge of the methods of other classes. Classes send inform the mediator when changes occur and the Mediator passes them on to any other classes that need to be informed.

Consequences of the Mediator Pattern
1. The Mediator makes loose coupling possible between objects in a program. It also localizes the behavior that otherwise would be distributed among several objects.
2. You can change the behavior of the program by simply changing or subclassing the Mediator.
3. The Mediator approach makes it possible to add new Colleagues to a system without having to change any other part of the program.
4. The Mediator solves the problem of each Command object needing to know too much about the objects and methods in the rest of a user interface.
5. The Mediator can become monolithic in complexity, making it hard to change and maintain. Sometimes you can improve this situation by revising the responsibilities you have given the Mediator. Each object should carry out it’s own tasks and the Mediator should only manage the
interaction between objects.
6. Each Mediator is a custom-written class that has methods for each Colleague to call and knows what methods each Colleague has available. This makes it difficult to reuse Mediator code in different projects. On the other hand, most Mediators are quite simple and writing this code is far easier than managing the complex object interactions any other way.

Implementation Issues
The Mediator pattern we have described above acts as a kind of Observer pattern, observing changes in the Colleague elements. Another approach is to have a single interface to your Mediator, and pass that method various constants or objects which tell the Mediator which operations to perform. In the same fashion, you could have a single Colleague interface that each Colleague would implement, and each Colleague would then decide what operation it was to carry out.
Mediators are not limited to use in visual interface programs, however, it is their most common application. You can use them whenever you are faced with the problem of complex intercommunication between a number of objects.

Memento pattern
Suppose you would like to save the internal state of an object so you can restore it later. Ideally, it should be possible to save and restore this state without making the object itself take care of this task, and without violating encapsulation. This is the purpose of the Memento pattern.

Motivation
Objects frequently expose only some of their internal state using public methods, but you would still like to be able to save the entire state of an object because you might need to restore it later. In some cases, you could obtain enough information from the public interfaces (such as the drawing position of graphical objects) to save and restore that data. In other cases, the color, shading, angle and connection relationship to other graphical objects need to be saved and this information is not readily available. This sort of information saving and restoration is common in systems that need to support

Undo commands.
If all of the information describing an object is available in public variables, it is not that difficult to save them in some external store. However, making these data public makes the entire system vulnerable to change by external program code, when we usually expect data inside an object to be private and encapsulated from the outside world.

The Memento pattern attempts to solve this problem by having privileged access to the state of the object you want to save. Other objects have only a more restricted access to the object, thus preserving their encapsulation. This pattern defines three roles for objects:
1. The Originator is the object whose state we want to save.
2. The Memento is another object that saves the state of the Originator.
3. The Caretaker manages the timing of the saving of the state, saves the Memento and, if needed, uses the Memento to restore the state of the Originator.

Consequences of the Memento
The Memento provides a way to preserve the state of an object while preserving encapsulation, in languages where this is possible. Thus, data that only the Originator class should have access to effectively remains private. It also preserves the simplicity of the Originator class by delegating the saving and restoring of information to the Memento class. On the other hand, the amount of information that a Memento has to save might be quite large, thus taking up fair amounts of storage. This further has an effect on the Caretaker class (here the Mediator) which may have to design strategies to limit the number of objects for which it saves state. In our simple example, we impose no such limits. In cases where objects change in a predictable manner, each Memento may be able to get by with saving only incremental changes of an object’s state.

Other Kinds of Mementos
While supporting undo/redo operations in graphical interfaces is one significant use of the Memento pattern, you will also see Mementos used in database transactions. Here they save the state of data in a transaction where it is necessary to restore the data if the transaction fails or is incomplete.

Observer pattern
Consequences of the Observer Pattern
Observers promote abstract coupling to Subjects. A subject doesn’t know the details of any of its observers. However, this has the potential disadvantage of successive or repeated updates to the Observers when there are a series of incremental changes to the data. If the cost of these updates is high, it may be necessary to introduce some sort of change management, so that the Observers are not notified too soon or too frequently. When one client makes a change in the underlying data, you need to decide which object will initiate the notification of the change to the other observers. If the Subject notifies all the observers when it is changed, each client is not responsible for remembering to initiate the notification. On the other hand, this can result in a number of small successive updates being triggered. If the clients tell the Subject when to notify the other clients, this cascading notification can be avoided, but the clients are left with the responsibility of telling the Subject when to send the notifications. If one client “forgets,” the program simply won’t work properly. Finally, you can specify the kind of notification you choose to send by defining a number of update methods for the Observers to receive depending on the type or scope of change. In some cases, the clients will thus be able to ignore some of these notifications

State pattern
The State pattern is used when you want to have an enclosing class switch between a number of related contained classes, and pass method calls on to the current contained class. Design Patterns suggests that the State pattern switches between internal classes in such a way that the enclosing object appears to change its class. In Java, at least, this is a bit of an exaggeration, but the actual purpose to which the classes are put can change significantly.

Many programmers have had the experience of creating a class which performs slightly different computations or displays different information based on the arguments passed into the class. This frequently leads to some sort of switch or if-else statements inside the class that determine which behavior to carry out. It is this inelegance that the State pattern seeks to replace.

Consequences of the State Pattern
1. The State pattern localizes state-specific behavior in an individual class for each state, and puts all the behavior for that state in a single object.
2. It eliminates the necessity for a set of long, look-alike conditional statements scattered through the program’s code.
3. It makes transition explicit. Rather than having a constant that specifies which state the program is in, and that may not always be checked correctly, this makes the change explicit by copying one of the states to the state variable.
4. State objects can be shared if they have no instance variables. Here only the Fill object has instance variables, and that color could easily be made an argument instead.
5. This approach generates a number of small class objects, but in the process, simplifies and clarifies the program.
6. In Java, all of the States must inherit from a common base class, and they must all have common methods, although some of those methods can be empty. In other languages, the states can be implemented by function pointers with much less type checking, and, of course, greater chance of error.

Strategy pattern
The Strategy pattern is much like the State pattern in outline, but a little different in intent. The Strategy pattern consists of a number of related algorithms encapsulated in a driver class called the Context. Your client program can select one of these differing algorithms or in some cases the Context might select the best one for you. The intent, like the State pattern, is to switch easily between algorithms without any monolithic conditional statements. The difference between State and Strategy is that the user generally chooses which of several strategies to apply and that only one strategy at a time is likely to be instantiated and active within the Context class. By contrast, as we have seen, it is likely that all of the different States will be active at once and switching may occur frequently between them. In addition, Strategy encapsulates several algorithms that do more or less the same thing, while State encapsulates related classes that each do something somewhat different. Finally, the concept of transition between different states is completely missing in the Strategy pattern.

Motivation
A program which requires a particular service or function and which has several ways of carrying out that function is a candidate for the Strategy pattern. Programs choose between these algorithms based on computational efficiency or user choice. There can be any number of strategies and more can be added and any of them can be changed at any time.

There are a number of cases in programs where we’d like to do the same thing in several different ways. Some of these are listed in the Smalltalk Companion:
· Save files in different formats.
· Compress files using different algorithms
· Capture video data using different compression schemes
· Use different line-breaking strategies to display text data.
· Plot the same data in different formats: line graph, bar chart or pie chart.

In each case we could imagine the client program telling a driver module (Context) which of these strategies to use and then asking it to carry out the operation.
The idea behind Strategy is to encapsulate the various strategies in a single module and provide a simple interface to allow choice between these strategies. Each of them should have the same programming interface, although they need not all be members of the same class hierarchy. However, they do have to implement the same programming interface.

Consequences of the Strategy Pattern
Strategy allows you to select one of several algorithms dynamically. These algorithms can be related in an inheritance hierarchy or they can be unrelated as long as they implement a common interface. Since the Context switches between strategies at your request, you have more flexibility than if you simply called the desired derived class. This approach also avoids the sort of condition statements than can make code hard to read ad maintain. On the other hand, strategies don’t hide everything. The client code must be aware that there are a number of alternative strategies and have some criteria for choosing among them. This shifts an algorithmic decision to the client programmer or the user.
Since there are a number of different parameters that you might pass to different algorithms, you have to develop a Context interface and strategy methods that are broad enough to allow for passing in parameters that are not used by that particular algorithm.

Template pattern
Whenever you write a parent class where you leave one or more of the methods to be implemented by derived classes, you are in essence using the Template pattern. The Template pattern formalizes the idea of defining an algorithm in a class, but leaving some of the details to be implemented in subclasses. In other words, if your base class is an abstract class, as often happens in these design patterns, you are using a simple form of the Template pattern.

Motivation
Templates are so fundamental, you have probably used them dozens of times without even thinking about it. The idea behind the Template pattern is that some parts of an algorithm are well defined and can be implemented in the base class, while other parts may have several implementations and are best left to derived classes. Another main theme is recognizing that there are some basic parts of a class that can be factored out and put in a base class so that they do not need to be repeated in several subclasses.

Kinds of Methods in a Template Class
A Template has four kinds of methods that you can make use of in derive classes:
1. Complete methods that carry out some basic function that all the subclasses will want to use, such as calcx and calcy in the above example. These are called Concrete methods.
2. Methods that are not filled in at all and must be implemented in derived classes. In Java , you would declare these as abstract methods, and that is how they are referred to in the pattern description.
3. Methods that contain a default implementation of some operations, but which may be overridden in derived classes. These are called Hook methods. Of course this is somewhat
arbitrary, because in Java you can override any public or protected method in the derived class, but Hook methods are intended to be overridden, while Concrete methods are not.
4. Finally, a Template class may contain methods which themselves call any combination of abstract, hook and concrete methods. These methods are not intended to be overridden, but describe an algorithm without actually implementing its details. Design Patterns refers to these as Template methods.

Summary and Consequences
Template patterns occur all the time in OO software and are neither complex nor obscure in intent. They are normal part of OO programming and you shouldn’t try to make them more abstract than they actually are.
The first significant point is that your base class may only define some of the methods it will be using, leaving the rest to be implemented in the derived classes. The second major point is that there may be methods in the base class which call a sequence of methods, some implemented in the base class and some implemented in the derived class. This Template method defines a general algorithm, although the details may not be worked out completely in the base class.
Template classes will frequently have some abstract methods that you must override in the derived classes, and may also have some classes with a simple “place-holder” implementation that you are free to override where this is appropriate. If these place-holder classes are called from another method in the base class, then we refer to these overridable methods are “Hook” methods.

Visitor pattern
The Visitor pattern turns the tables on our object-oriented model and creates an external class to act on data in other classes. This is useful if there are a fair number of instances of a small number of classes and you want to perform some operation that involves all or most of them.

Motivation
While at first it may seem “unclean” to put operations that should be inside a class in another class instead, there are good reasons for doing it. Suppose each of a number of drawing object classes has similar code for drawing itself. The drawing methods may be different, but they probably all use underlying utility functions that we might have to duplicate in each class. Further, a set of closely related functions is scattered throughout a number of different classes

When to Use the Visitor Pattern
You should consider using a Visitor pattern when you want to perform an operation on the data contained in a number of objects that have different interfaces. Visitors are also valuable if you have to perform a number of unrelated operations on these classes. On the other hand, as we will see below, Visitors are a good choice only when you do not expect many new classes to be added to your program.

Sample Code
We have a simple Employee object which maintains a record of the employee’s name, salary, vacation taken and number of sick days taken. A simple version of this class is:

public class Employee
{
int sickDays, vacDays;
float Salary;
String Name;
public Employee(String name, float salary,
int vacdays, int sickdays)
{
vacDays = vacdays; sickDays = sickdays;
Salary = salary; Name = name;
}
public String getName() { return Name; }
public int getSickdays() { return sickDays; }
public int getVacDays() { return vacDays; }
public float getSalary() { return Salary; }
public void accept(Visitor v) { v.visit(this); }
}

Note that we have included the accept method in this class. Now let’s suppose that we want to prepare a report of the number of vacation days that all employees have taken so far this year. We could just write some code in the client to sum the results of calls to each Employee’s getVacDays function, or we could put this function into a Visitor.
Since Java is a strongly typed language, your base Visitor class needs to have a suitable abstract visit method for each kind of class in your program. In this first simple example, we only have Employees, so our basic abstract Visitor class is just

public abstract class Visitor
{
public abstract void visit(Employee emp);
}

Notice that there is no indication what the Visitor does with each class in either the client classes or the abstract Visitor class. We can in fact write a whole lot of visitors that do different things to the classes in our program. The Visitor we are going to write first just sums the vacation data
for all our employees:

public class VacationVisitor extends Visitor
{
protected int total_days;
public VacationVisitor() { total_days = 0; }
//-----------------------------
public void visit(Employee emp)
{
total_days += emp.getVacDays();
}
//-----------------------------
public int getTotalDays()
{
return total_days;
}
}

Visiting the Classes
Now, all we have to do to compute the total vacation taken is to go through a list of the employees and visit each of them, and then ask the Visitor for the total.

VacationVisitor vac = new VacationVisitor();
for (int i = 0; i < employees.length; i++)
{
employees[i].accept(vac);
}
System.out.println(vac.getTotalDays());

Let’s reiterate what happens for each visit:

1. We move through a loop of all the Employees.
2. The Visitor calls each Employee’s accept method.
3. That instance of Employee calls the Visitor’s visit method.
4. The Visitor fetches the vacation days and adds them into the total.
5. The main program prints out the total when the loop is complete.

Double Dispatching
No article on the Visitor pattern is complete without mentioning that you are really dispatching a method twice for the Visitor to work. The Visitor calls the polymorphic accept method of a given object, and the accept method calls the polymorphic visit method of the Visitor. It this bidirectional calling that allows you to add more operations on any class that has an accept method, since each new Visitor class we write can carry out whatever operations we might think of using the data available in these classes.

Traversing a Series of Classes
The calling program that passes the class instances to the Visitor must know about all the existing instances of classes to be visited and must keep them in a simple structure such as an array or Vector. Another possibility would be to create an Enumeration of these classes and pass it to the Visitor. Finally, the Visitor itself could keep the list of objects that it is to visit. In our simple example program, we used an array of objects, but any of the other methods would work equally well.

Consequence of the Visitor Pattern
The Visitor pattern is useful when you want to encapsulate fetching data from a number of instances of several classes. Design Patterns suggests that the Visitor can provide additional functionality to a class without changing it. We prefer to say that a Visitor can add functionality to a collection of classes and encapsulate the methods it uses. The Visitor is not magic, however, and cannot obtain private data from classes: it is limited to the data available from public methods. This might force you to provide public methods that you would otherwise not have provided. However, it can obtain data from a disparate collection of unrelated classes and utilize it to present the results of a global calculation to the user program.

It is easy to add new operations to a program using Visitors, since the Visitor contains the code instead of each of the individual classes. Further, Visitors can gather related operations into a single class rather than forcing you to change or derive classes to add these operations. This can make the program simpler to write and maintain.

Visitors are less helpful during a program’s growth stage, since each time you add new classes which must be visited, you have to add an abstract visit operation to the abstract Visitor class, and you must add an implementation for that class to each concrete Visitor you have written. Visitors can be powerful additions when the program reaches the point where many new classes are unlikely. Visitors can be used very effectively in Composite systems

Monday, December 27, 2004

Patterns 2 : Structural patterns

Some of this material is from the java patterns book by James cooper.*

Adapter pattern
The Adapter pattern is used to convert the programming interface of one class into that of another. We use adapters whenever we want unrelated classes to work together in a single program. The concept of an adapter is thus pretty simple; we write a class that has the desired interface and then make it communicate with the class that has a different interface.

There are two ways to do this: by inheritance, and by object composition. In the first case, we derive a new class from the nonconforming one and add the methods we need to make the new derived class match the desired interface. The other way is to include the original class inside the new one and create the methods to translate calls within the new class. These two approaches, termed class adapters and object adapters are both fairly easy to implement in Java.

Bridge pattern
The Bridge pattern is used to separate the interface of class from its implementation, so that either can be varied separately. At first sight, the bridge pattern looks much like the Adapter pattern, in that a class is used to convert one kind of interface to another. However, the intent of the Adapter pattern is to make one or more classes’ interfaces look the same as that of a particular class. The Bridge pattern is designed to separate a class’s interface from its implementation, so that you can vary or replace the implementation without changing the client code.

Consequences of the Bridge Pattern
1. The Bridge pattern is intended to keep the interface to your client program constant while allowing you to change the actual kind of class you display or use. This can prevent you from recompiling a complicated set of user interface modules, and only require that you recompile the bridge itself and the actual end display class.

2. You can extend the implementation class and the bridge class separately, and usually without much interaction with each other.

3. You can hide implementation details from the client program much more easily.

Composite pattern.
Frequently programmers develop systems in which a component may be an individual object or it may represent a collection of objects. The Composite pattern is designed to accommodate both cases. You can use the Composite to build part-whole hierarchies or to construct data representations of trees. In summary, a composite is a collection of objects, any one of which may be either a composite, or just a primitive object. In tree nomenclature, some objects may be nodes with additional branches and some may be leaves.

The problem that develops is the dichotomy between having a single, simple interface to access all the objects in a composite, and the ability to distinguish between nodes and leaves. Nodes have children and can have children added to them, while leaves do not at the moment have children, and in some implementations may be prevented from having children added to them.

Some authors have suggested creating a separate interface for nodes
and leaves, where a leaf could have the methods

public String getName();
public String getValue();

and a node could have the additional methods:

public Enumeration elements();
public Node getChild(String nodeName);
public void add(Object obj);
public void remove(Object obj);

This then leaves us with the programming problem of deciding which elements will be which when we construct the composite.

However, Design Patterns suggests that each element should have the same interface, whether
it is a composite or a primitive element. This is easier to accomplish, but we are left with the question of what the getChild() operation should accomplish when the object is actually a leaf.

Java makes this quite easy for us, since every node or leaf can return an Enumeration of the contents of the Vector where the children are stored. If there are no children, the hasMoreElements() method returns false at once. Thus, if we simply obtain the Enumeration from each element, we can quickly determine whether it has any children by checking the
hasMoreElements() method.

Decorator Pattern
The Decorator pattern provides us with a way to modify the behavior of individual objects without having to create a new derived class. Suppose we have a program that uses eight objects, but three of them need an additional feature. You could create a derived class for each of these objects, and in many cases this would be a perfectly acceptable solution. However, if each of these three objects require different modifications, this would mean creating three derived classes. Further, if one of the classes has features of both of the other classes, you begin to create a complexity that is both confusing and unnecessary.

For example, suppose we wanted to draw a special border around some of the buttons in a toolbar. If we created a new derived button class, this means that all of the buttons in this new class would always have this same new border, when this might not be our intent. Instead, we create a Decorator class that decorates the buttons. Then we derive any number of specific Decorators from the main Decorator class, each of which performs a specific kind of decoration.

In order to decorate a button, the Decorator has to be an object derived from the visual environment, so it can receive paint method calls and forward calls to other useful graphic methods to the object that it is decorating. This is another case where object containment is favored over object inheritance. The decorator is a graphical object, but it contains the object it is decorating. It may intercept some graphical method calls, perform some additional computation and may pass them on to the underlying object it is decorating.

Non-Visual Decorators
Decorators, of course, are not limited to objects that enhance visual classes. You can add or modify the methods of any object in a similar fashion. In fact, non-visual objects are usually easier to decorate, because there are usually fewer methods to intercept and forward.

While coming up with a simple example is difficult, a series of Decorators do occur naturally in the java.io classes. Note the following in the Java documentation:

The class FilterInputStream itself simply overrides all methods of InputStream with versions that pass all requests to the underlying input stream. Subclasses of FilterInputStream may further override some of these methods as well as provide additional methods and fields.

The FilterInputStream class is thus a Decorator that can be wrapped around any input stream class. It is essentially an abstract class that doesn’t do any processing, but provides a layer where the relevant methods have been duplicated. It normally forwards these method calls to the enclosed parent stream class.

The interesting classes derived from FilterInputStream include:-

BufferedInputStream: Adds buffering to stream so that every call does not cause I/O to occur.

CheckedInputStream: Maintains a checksum of bytes as they are read

DataInputStream: Reads primitive types (Long, Boolean, Float, etc.) from the input stream.

DigestInputStream: Computes a MessageDigest of any input stream.

InflaterInputStream: Implements methods for uncompressing data.

PushbackInputStream: Provides a buffer where data can be “unread,” if during parsing you discover you need to back up.

These decorators can be nested, so that a pushback, buffered input stream is quite possible.

Decorators, Adapters and Composites
There is an essential similarity among these classes that you may have recognized.

Adapters also seem to “decorate” an existing class. However, their function is to change the interface of one or more classes to one that is more convenient for a particular program.

Decorators add methods to particular instances of classes, rather than to all of them. You could also imagine that a composite consisting of a single item is essentially a decorator.
Once again, however, the intent is different

Consequences of the Decorator Pattern
The Decorator pattern provides a more flexible way to add responsibilities to a class than by using inheritance, since it can add these responsibilities to selected instances of the class. It also allows you to customize a class without creating subclasses high in the inheritance hierarchy. Design Patterns points out two disadvantages of the Decorator pattern One is that a Decorator and its enclosed component are not identical. Thus tests for object type will fail. The second is that Decorators can lead to a system with “lots of little objects” that all look alike to the programmer trying to maintain the code. This can be a maintenance headache.

Decorator and Façade evoke similar images in building architecture,but in design pattern terminology, the Façade is a way of hiding a complex system inside a simpler interface, while Decorator adds function by wrapping a class.

Facade Pattern
The Façade pattern allows you to simplify complexity by providing a simplified interface to subsystems. This simplification may in some cases reduce the flexibility of the underlying classes, but usually provides all the function needed for all but the most sophisticated users. These users can still, of course, access the underlying classes and methods.

FlyWeight Pattern
There are cases in programming where it seems that you need to generate a very large number of small class instances to represent data. Sometimes you can greatly reduce the number of different classes that you need to instantiate if you can recognize that the instances are fundamentally the same except for a few parameters. If you can move those variables outside the class instance and pass them in as part of a method call, the number of separate instances can be greatly reduced.

The Flyweight design pattern provides an approach for handling such classes. It refers to the instance’s intrinsic data that makes the instance unique, and the extrinsic data which is passed in as arguments. The Flyweight is appropriate for small, fine-grained classes like individual characters or icons on the screen. For example, if you are drawing a series of icons on the screen in a folder window, where each represents a person or data file, it does not make sense to have an individual class instance for each of them that remembers the person’s name and the icon’s screen position. Typically these icons are one of a few similar images and the position where they are drawn is calculated dynamically based on the window’s size in any case.

In another example in Design Patterns, each character in a font is represented as a single instance of a character class, but the positions where the characters are drawn on the screen are kept as external data so that there needs to be only one instance of each character, rather than one for each appearance of that character.

Sharable Objects
The Smalltalk Companion points out that sharable objects are much like Flyweights, although the purpose is somewhat different. When you have a very large object containing a lot of complex data, such as tables or bitmaps, you would want to minimize the number of instances of that object. Instead, in such cases, you’d return one instance to every part of the program that asked for it and avoid creating other instances.

A problem with such sharable objects occurs when one part of a program wants to change some data in a shared object. You then must decide whether to change the object for all users, prevent any change, or create a new instance with the changed data. If you change the object for every instance, you may have to notify them that the object has changed.

Sharable objects are also useful when you are referring to large data systems outside of Java, such as databases.

Proxy Pattern
The Proxy pattern is used when you need to represent a complex object by a simpler one. If creating an object is expensive in time or computer resources, Proxy allows you to postpone this creation until you need the actual object. A Proxy usually has the same methods as the object it
represents, and once the object is loaded, it passes on the method calls from the Proxy to the actual object.

There are several cases where a Proxy can be useful:
1. If an object, such as a large image, takes a long time to load.
2. If the object is on a remote machine and loading it over the network may be slow, especially during peak network load periods.
3. If the object has limited access rights, the proxy can validate the access permissions for that user.

Proxies can also be used to distinguish between requesting an instance of an object and the actual need to access it. For example, program initialization may set up a number of objects which may not all be used right away. In that case, the proxy can load the real object only when it is needed.

Let’s consider the case of a large image that a program needs to load and display. When the program starts, there must be some indication that an image is to be displayed so that the screen lays out correctly, but the actual image display can be postponed until the image is completely loaded. This is particularly important in programs such as word processors and web browsers that lay out text around the images even before the images are available.

An image proxy can note the image and begin loading it in the background, while drawing a simple rectangle or other symbol to represent the image’s extent on the screen before it appears. The proxy can even delay loading the image at all until it receives a paint request, and only then begin the process.

Comparison with Related Patterns
Both the Adapter and the Proxy constitute a thin layer around an object. However, the Adapter provides a different interface for an object, while the Proxy provides the same interface for the object, but interposes itself where it can save processing effort.

A Decorator also has the same interface as the object it surrounds, but its purpose is to add additional (usually visual) function to the original object. A proxy, by contrast, controls access to the contained class.

Sunday, December 26, 2004

Patterns 1 : Creational patterns

Some of this material is from the java patterns book by James cooper.*

Factory Pattern

Factory patterns helps localizing the generation of certain obects to one place in code. That way we have control over how and what object is created.

Factory Method

It provides a simple decision making class that returns one of several possible subclasses of an abstract base class depending on the data that are provided.

When to Use a Factory Pattern
You should consider using a Factory pattern when
· A class can’t anticipate which kind of class of objects it must create.
· A class uses its subclasses to specify which objects it creates.
· You want to localize the knowledge of which class gets created.

There are several similar variations on the factory pattern to recognize.
1. The base class is abstract and the pattern must return a complete working class.
2. The base class contains default methods and is only subclassed for cases where the default methods are insufficient.
3. Parameters are passed to the factory telling it which of several class types to return. In this case the classes may share the same method names but may do something quite different.

Abstract Factory Method
It provides an interface to create and return one of several families of related objects.

The Abstract Factory pattern is one level of abstraction higher than the factory pattern. You can use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several factories.

Consequences of Abstract Factory
One of the main purposes of the Abstract Factory is that it isolates the concrete classes that are generated. The actual class names of these classes are hidden in the factory and need not be known at the client level at all. Because of the isolation of classes, you can change or interchange these product class families freely. Further, since you generate only one kind of concrete class, this system keeps you for inadvertently using classes from different families of products. However, it is some effort to add new class families, since you need to define new, unambiguous conditions that cause such a new family of classes to be returned.

Builder Pattern
It separates the construction of a complex object from its representation, so that several different representations can be created depending on the needs of the program.

Prototype Pattern
It starts with an initialized and instantiated class and copies or clones it to make new instances rather than creating new instances.
The Protoype pattern is used when creating an instance of a class is very time-consuming or complex in some way. Then, rather than creating more instances, you make copies of the original instance, modifying them as appropriate.

Noramlly in java you use clone method to shallwo copy an object.

MyObject mNew = (MyObject)mOld.clone();

But to do a deepcopy you do this. Remember that the Object tobeDeepCloned has to have all of its child objects as serializable.

public Object deepClone(Object tobeDeepCloned)
{
try{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(b);
out.writeObject(

tobeDeepCloned
);
ByteArrayInputStream bIn = new ByteArrayInputStream(b.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bIn);
return (oi.readObject());
}
catch (Exception e)
{
System.out.println("exception:"+e.getMessage());
return null;
}
}

Singleton Pattern
It is a class of which there can be no more than one instance. It provides a single global point of access to that instance.

Tuesday, December 21, 2004

Aspect oriented programming with CGLIB


1 Introduction and background

2 Purpose of this article
3 Prerequisites
4 Topic 1: Measure the time taken by method calls
4.1 SimpleClass class
4.2 TimeInterceptor class 4
4.3 MethodTimeGenerator class 4
4.4 Main class 5
4.5 Topic Conclusion 6
5 Topic 2: Dynamic connection allocation 6
5.1 DaoTagInterface 6
5.2 DAO class 6
5.3 DaoInterceptor class 7
5.4 DaoGenerator class 9
5.5 DaoFactory class 9
5.6 Main class 9
5.7 Topic Conclusion 10
6 Conclusion. 11
7 Drawbacks 11

1 Introduction and background

Aspect oriented programming has been talked about greatly recently. There are developers who think that it is a great idea and also an equal number who think that it is not as it breaks the principles of Object oriented programming.

2 Purpose of this article

During the last few years I faced some issues that were present across the entire code base.
I thought must have a clean/fast way of solving but I did not have an answer until I read what aspect oriented programming was.
I will present two such problems and their solutions.
I investigated CGLIB after reading this article http://www.onjava.com/lpt/a/5250 by Eugene Kuleshov at Onjava.com.
This paper is a result of that investigation.

3 Prerequisites

Cglib 2 jar file in the class path. It can be downloaded from here: http://sourceforge.net/project/showfiles.php?group_id=56933

4 Topic 1: Measure the time taken by method calls

One of the issues was measuring the exact time taken by each of my method calls, so as to better solve performance issues.
I wanted to do this in a way, so as to be able to switch it on/off as and when required.

Here are the classes

4.1 SimpleClass class

package com.test.methodtimetest;
/**
* @author suchakj
*/
public class SimpleClass {
public void simpleMethod() {
System.out.println("Hello In Simple Method");
}
}
This is just a class with a single method that prints hello.

4.2 TimeInterceptor class

package com.test.methodtimetest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* @author suchakj
*/
public class TimeInterceptor implements MethodInterceptor {
/* This is the method that intecepts a method, it automatically adds the start and end time
* for a method.
* @see net.sf.cglib.proxy.MethodInterceptor#intercept
* (java.lang.Object, java.lang.reflect.Method, java.lang.Object[],
* net.sf.cglib.proxy.MethodProxy)
*/
public Object intercept(
Object obj,
Method method,
Object[] args,
MethodProxy proxy)
throws Throwable {
System.out.println("Before method : " + method + " Time : " + new Timestamp(System.currentTimeMillis()));
Object o = proxy.invokeSuper(obj,args);
System.out.println("After method : " + method + " Time : " + new Timestamp(System.currentTimeMillis()));
return o;
}
}
}

This is a class that implements the Cglib MethodInterceptor interface. The MethodInterceptor interface implements a single method called intercept(). The cglib framework calls this method when a particular Object method is intercepted.
As we can see that the intercept method , adds a Timestamp, before and after the method call. The method is called using proxy.invokeSuper(obj,args); . This takes care of the method timing in one central place.

4.3 MethodTimeGenerator class

package com.test.methodtimetest;
import net.sf.cglib.proxy.Enhancer;
/**
* @author suchakj
*/
public class MethodTimeGenerator {
public static Object getTimeEnhancedObject(Class clazz){
Enhancer e = new Enhancer();
e.setSuperclass(clazz);
e.setCallback(new TimeInterceptor());
return e.create();
}
}

This is the main generator. This class uses the cglib Enhancer class to join the method interceptor class with the any class(in our case it is SimpleClass).

4.4 Main class

package com.test;
import com.test.daoconntest.DAO;
import com.test.daoconntest.DaoFactory;
import com.test.daoconntest.DaoInterceptor;
import com.test.methodtimetest.MethodTimeGenerator;
import com.test.methodtimetest.SimpleClass;
/**
* @author suchakj
*/

public class Main {

public static void testMethodTimeTest(){
//this could come from a factory.
SimpleClass s = (SimpleClass)MethodTimeGenerator.getTimeEnhancedObject(SimpleClass.class);
s.simpleMethod();
}

public static void main(String[] args) {
testMethodTimeTest();
}

}

This the test class. This class is testing our implementation.

Here is the output.
---------------------------------------------------------------------------------------------------------------
Before method : public void com.test.methodtimetest.SimpleClass.simpleMethod() Time : 2004-12-17 14:20:36.046
Hello In Simple Method
After method : public void com.test.methodtimetest.SimpleClass.simpleMethod() Time : 2004-12-17 14:20:36.14
---------------------------------------------------------------------------------------------------------------

4.5 Topic Conclusion

The above code shows how simple it is to add time delay interceptor to a class. It is not at all intrusive on the class that is being intercepted for recording the time delay.

5 Topic 2: Dynamic connection allocation

The importance of connection pools cannot be underestimated.
The main issue I faced in an environment was whether a method returned the connection back to the pool after it had finished using the same.
I wanted to do this in a way, so as to do this in a central place also.
This example will also modify the arguments passed to the method.

Here are the classes

5.1 DaoTagInterface

package com.test.daoconntest;
/**
* @author suchakj
*
* This is just a tag inteface
*/

public interface DaoTagInterface {
}

This is just a tagging interface for DAO classes.

5.2 DAO class

package com.test.daoconntest;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author suchakj
*/

public class DAO implements DaoTagInterface{

public void daoMethod(String someParam,Object connection){
System.out.println("In Dao Method");
if(connection!=null){
System.out.println("Got a Valid connection that i can use");
}else{
System.out.println("No connection");
}

/* try {
Statement s = ((Connection)connection).createStatement();
ResultSet r = s.executeQuery("Select * from SomeTable");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}

This is the Data access class. It does the call to the database.

5.3 DaoInterceptor class

package com.test.daoconntest;
import java.lang.reflect.Method;
import java.sql.Connection;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
* @author suchakj
*/

public class DaoInterceptor implements MethodInterceptor {

/* This is the method that intecepts dao methods, it automatically adds connection objects,
* to the method from a pool and also returns them back to the pool
* @see net.sf.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], net.sf.cglib.proxy.MethodProxy)
*/

public Object intercept(Object obj, Method method, Object[] args,

MethodProxy proxy) throws Throwable {

// Connection connection = getConnection();
Object connection = getConnection();
args[args.length -1] = connection;
proxy.invokeSuper(obj,args);
returnConnection(connection);
return null;
}

/**
* @return Connection
*/

private Object getConnection() {
// get the connection from some Connection pool
System.out.println("Getting connection from pool ...");
return new Object();// this is just for testing this should be a java.sql.connection object
}

/**
* @param Connection
*/

private void returnConnection(Object c) {
System.out.println("returning connection to pool ...");
// Return the connection back to the pool..
}
}

This is a class that implements the Cglib MethodInterceptor interface. The MethodInterceptor interface implements a single method called intercept(). The cglib framework calls this method when a particular Object method is intercepted.
The getConnection() and returnConnection() methods can get and return connections from a pool.
As we can see this class changes the arguments passed to the method as
“Object connection = getConnection();”
“args[args.length -1] = connection;”
“proxy.invokeSuper(obj,args);”
Thus a “connection object” should be passed to the method daoMethod(String someParam,Object connection). We shall see this in the test.

5.4 DaoGenerator class

package com.test.daoconntest;
import net.sf.cglib.proxy.Enhancer;
/**
* @author suchakj
*/

public class DaoGenerator {
public static Object getTimeEnhancedObject(Class clazz){
Enhancer e = new Enhancer();
e.setSuperclass(clazz);
e.setCallback(new DaoInterceptor());
return e.create();
}
}

This is the main generator for the DAO interceptor. This class uses the cglib Enhancer class to join the interceptor class DaoInterceptor with the any dao class(in our case it is DAO class).

5.5 DaoFactory class

package com.test.daoconntest;

/**
* @author suchakj
*/

public class DaoFactory {
public static DaoTagInterface getDao(Class clazz) throws InstantiationException, IllegalAccessException {
return (DaoTagInterface) DaoGenerator.getTimeEnhancedObject(clazz);
}
}

This is a factory for generating DAO classes. It uses the DaoGenerator for generating Dao classes.

5.6 Main class


This the same test class as in the previous topic. This class is testing our implementation.

package com.test;
import com.test.daoconntest.DAO;
import com.test.daoconntest.DaoFactory;
import com.test.daoconntest.DaoInterceptor;
import com.test.methodtimetest.MethodTimeGenerator;
import com.test.methodtimetest.SimpleClass;

/**
* @author suchakj
*/

public class Main {

public static void testMethodTimeTest(){
//this could come from a factory.
SimpleClass s = (SimpleClass)MethodTimeGenerator.getTimeEnhancedObject(SimpleClass.class);
s.simpleMethod();
}

public static void testDaoConn(){
DAO d;
try {
d = (DAO)DaoFactory.getDao(DAO.class);
d.daoMethod("test",null);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
//testMethodTimeTest();
testDaoConn();
}


}

Here is the output.
---------------------------------------------------------------------------------------------------------------
Getting connection from pool ...
In Dao Method
Got a Valid connection that I can use
Returning connection to pool ...
---------------------------------------------------------------------------------------------------------------

5.7 Topic Conclusion

The above code shows how simple it is for a dao to give and return a connection from/to the connection pool, without writing such code in all the dao methods.Also the code for this is in a central place and can be modified as needed.

6 Conclusion.

Aspects of a code base , a framework can be cleanly coded using Aspect oriented programming. It can be coded in a non intrusive way using Cglib. Thus the result is Aspect code of a similar type in one central place and still applied to the objects that need the Aspect. The two aspects we talked about were getting connection and returning them to a connection pool, and timing methods for querying performance.

7 Drawbacks

Some of the drawbacks of what is explained above are.

1) There could be two or more dao method calls that want to use the same connection object for the reason of transactions. For this the solution could be that we check if the user has sent a connection and if he has then do not apply the interception

2) For both the topics a new Enhancer is created at each method call, it would be better to have a cache of a Hashmap or a WeakHashMap so that the impact of new Enhancer creation at every method call is reduced.

3) The daointerceptor assumes that the method will have a Connection param, which will be the last param, and also which will be ignored even if sent by the user.

Implementing a Frequency date time generator in java

The java calendar class does a lot of good things. As far as adding days to a date is concerened it has three methods.

set(f, value) : sets the field f which could be weekdday, month, year,etc. to the value specified.

add(f, delta) : adds detla to the field f which could be weekdday, month, year,etc.

roll(f, delta) : adds detla to the field f which could be weekdday, month, year,etc whichout changing the larger fields. For exmaple using roll to add 10 to the month value of Dec 31 2004 will roll to OCt 31 2004 as year being the larger will be the same.

For more details on these methods look at http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html.

The objective of this post to to reconcile the calendar class with the computation of custom frequencies like daily, weekly,monthing, biweekly etc..

I have written a class that uses the calendar to compute custom frequencies in a manner that helps the user get the next date, if he just supplies his current date and the frequency.

Beware ! Reading this class is not easy at all, however it can be very usefull.



import java.sql.Timestamp;
import java.util.Calendar;

/**
* This class generates a date/time based on a frequency.
* It accepts a range of frequencies, like Hourly, Monthy, Weekly,
* Yearly,BiWeekly, SemiMonthy,Quarterly and LastDayOfMonth and
* based on the frequency generates the next run date.
*
* @author suchakj
*/
public class RunFreqGenerator {

/**
* This interface holds the string values for all frequencies.
* The frequnecies are Hourly, Monthy, Weekly, Yearly,BiWeekly, SemiMonthy,
* Quarterly and LastDayOfMonth.
*
*/
public interface RunFreqInterface {
public static final String RUN_FREQ_HOURLY = "H";

public static final String RUN_FREQ_DAILY = "D";

public static final String RUN_FREQ_MONTHLY = "M";

public static final String RUN_FREQ_WEEKLY = "W";

public static final String RUN_FREQ_YEARLY = "Y";

public static final String RUN_FREQ_BIWEEKLY = "B";

public static final String RUN_FREQ_SEMIMONTHLY = "S";

public static final String RUN_FREQ_QUARTERLY = "Q";

public static final String RUN_FREQ_HALFYEARLY = "L";

public static final String LAST_DAY_OF_MONTH = "LD";
}

/**
* Every frequency needs a certain set of parameters to determine the next
* run date.
*
* This class holds the frequency related parameters based on the frequency
* type.
*
*/
public class DateFreqHolder {

// The date for the next run.
private Timestamp nextDate;

// A frequency based on the RunFreqInterface attributes.
private String freq;

/*
* The day of the run i.e Monday, Wednesday etc. It is eighter the full
* name or the first three letters of the day name.
*/
private String run_day;

/*
* The numerical day of the month on which the the task is run for the
* first time.
*/
private String first_run_date;

/*
* The month of the run i.e January,February etc. It is eighter the full
* name or the first three letters of the month name.
*/
private String run_month;

/*
* The numerical day of the month on which the task is run for a
* second time.
*/
private String second_run_date;

public String getFirst_run_date() {
return first_run_date;
}

public void setFirst_run_date(String first_run_date) {
this.first_run_date = first_run_date;
}

public String getRun_month() {
return run_month;
}

public void setRun_month(String run_month) {
this.run_month = run_month;
}

public String getRun_day() {
return run_day;
}

public void setRun_day(String run_day) {
this.run_day = run_day;
}

public String getSecond_run_date() {
return second_run_date;
}

public void setSecond_run_date(String second_run_date) {
this.second_run_date = second_run_date;
}

public String getFreq() {
return freq;
}

public Timestamp getNextDate() {
return nextDate;
}

public void setFreq(String freq) {
this.freq = freq;
}

public void setNextDate(Timestamp nextDate) {
this.nextDate = nextDate;
}
}

/*
* Gets the next date based on the data in the DateFreqHolder
*
*/
public static Timestamp getNextDate(DateFreqHolder holder) throws Exception {

Timestamp previousRunDate = holder.getNextDate();
if (previousRunDate == null) {
throwNullVarException("nextRundate");
}
String runFreq = holder.getFreq();
if (runFreq == null) {
throwNullVarException("run freq");
}
Calendar cal = Calendar.getInstance();
cal.setTime(previousRunDate);

if (RunFreqInterface.RUN_FREQ_HOURLY.equals(runFreq)) {
return addHours(cal, 1);
}

if (RunFreqInterface.RUN_FREQ_DAILY.equals(runFreq)) {
return addHours(cal, 24);
}

if (RunFreqInterface.RUN_FREQ_WEEKLY.equals(runFreq)) {
String runDay = holder.getRun_day();
if (runDay == null) {
throwNullVarForFreqException("run day", RunFreqInterface.RUN_FREQ_WEEKLY);
}

return addWeeks(cal, cal.get(Calendar.DAY_OF_WEEK),
getWeekday(runDay), 1);
}

if (RunFreqInterface.RUN_FREQ_MONTHLY.equals(runFreq)) {
String runDate = holder.getFirst_run_date();
if (runDate == null) {
throwNullVarForFreqException("run date", RunFreqInterface.RUN_FREQ_MONTHLY);
}
return addMonth(cal, runDate);
}

if (RunFreqInterface.RUN_FREQ_QUARTERLY.equals(runFreq)) {
String runDate = holder.getFirst_run_date();
if (runDate == null) {
throwNullVarForFreqException("run date", RunFreqInterface.RUN_FREQ_QUARTERLY);
}
return addQuarter(cal, cal.get(Calendar.MONTH), runDate);
}

if (RunFreqInterface.RUN_FREQ_YEARLY.equals(runFreq)) {
String runDate = holder.getFirst_run_date();
String runMonth = holder.getRun_month();
if (runDate == null) {
throwNullVarForFreqException("run date", RunFreqInterface.RUN_FREQ_YEARLY);
}
if (runMonth == null) {
throwNullVarForFreqException("run month", RunFreqInterface.RUN_FREQ_YEARLY);
}
return addMonths(cal, cal.get(Calendar.MONTH), getMonth(runMonth),
runDate, 12);
}

if (RunFreqInterface.RUN_FREQ_BIWEEKLY.equals(runFreq)) {
String runDay = holder.getRun_day();
if (runDay == null) {
throwNullVarForFreqException("run day", RunFreqInterface.RUN_FREQ_BIWEEKLY);
}
return addWeeks(cal, cal.get(Calendar.DAY_OF_WEEK),
getWeekday(runDay), 2);
}

if (RunFreqInterface.RUN_FREQ_SEMIMONTHLY.equals(runFreq)) {
String runDateString = holder.getFirst_run_date();
String secondRunDateString = holder.getSecond_run_date();
if (runDateString == null) {
throwNullVarForFreqException("run date",
RunFreqInterface.RUN_FREQ_SEMIMONTHLY);
}
if (secondRunDateString == null) {
throwNullVarForFreqException("second run date",
RunFreqInterface.RUN_FREQ_SEMIMONTHLY);
}
if (RunFreqInterface.LAST_DAY_OF_MONTH.equals(runDateString)) {
throw new Exception("DateFreqHolder cannot have "
+ "first rundate as last day of the month ::"
+ RunFreqInterface.RUN_FREQ_SEMIMONTHLY);
}
int runDate = (new Integer(runDateString)).intValue();
int secondRunDate = 0;

if (RunFreqInterface.LAST_DAY_OF_MONTH.equals(secondRunDateString)) {
secondRunDate = 31;
} else {
secondRunDate = (new Integer(secondRunDateString)).intValue();
}
if (secondRunDate > runDate) {
throw new Exception("DateFreqHolder cannot have "
+ "first rundate less than the second run date "
+ "for task type ::: "
+ RunFreqInterface.RUN_FREQ_SEMIMONTHLY);
}

int previousRunDateInt = cal.get(Calendar.DAY_OF_MONTH);

if (previousRunDateInt < runDate) {
cal.set(Calendar.DAY_OF_MONTH, runDate);
return new Timestamp(cal.getTime().getTime());
} else if ((previousRunDateInt >= runDate)
& (previousRunDateInt > secondRunDate)) {
cal.set(Calendar.DAY_OF_MONTH, secondRunDate);
return new Timestamp(cal.getTime().getTime());
} else if (previousRunDateInt >= secondRunDate) {
return addMonth(cal, runDateString);
}
}

throw new Exception("DateFreqHolder does not have a proper fequency ::");
}

/*
* This method returns the int value of the month based on the string
* supplied. Please note valid month strings are the full month name or the
* first three letters of the month name. For example January, February or
* Jan, Feb.
*
* This method is not case sensitive.
*
*/
private static int getMonth(String month) throws Exception {
if ("JAN".equalsIgnoreCase(month) || "JANUARY".equalsIgnoreCase(month)) {
return Calendar.JANUARY;
}
if ("FEB".equalsIgnoreCase(month) || "FEBRUARY".equalsIgnoreCase(month)) {
return Calendar.FEBRUARY;
}
if ("MAR".equalsIgnoreCase(month) || "MARCH".equalsIgnoreCase(month)) {
return Calendar.MARCH;
}
if ("APR".equalsIgnoreCase(month) || "APRIL".equalsIgnoreCase(month)) {
return Calendar.APRIL;
}
if ("MAY".equalsIgnoreCase(month)) {
return Calendar.MAY;
}
if ("JUN".equalsIgnoreCase(month) || "JUNE".equalsIgnoreCase(month)) {
return Calendar.JUNE;
}
if ("JUL".equalsIgnoreCase(month) || "JULY".equalsIgnoreCase(month)) {
return Calendar.JULY;
}
if ("AUG".equalsIgnoreCase(month) || "AUGUST".equalsIgnoreCase(month)) {
return Calendar.AUGUST;
}
if ("SEP".equalsIgnoreCase(month)
|| "SEPTEMBER".equalsIgnoreCase(month)) {
return Calendar.SEPTEMBER;
}
if ("OCT".equalsIgnoreCase(month) || "OCTOBER".equalsIgnoreCase(month)) {
return Calendar.OCTOBER;
}
if ("NOV".equalsIgnoreCase(month) || "NOVEMBER".equalsIgnoreCase(month)) {
return Calendar.NOVEMBER;
}
if ("DEC".equalsIgnoreCase(month) || "DECEMBER".equalsIgnoreCase(month)) {
return Calendar.DECEMBER;
}
throw new Exception("Month cannot be :: " + month);
}

/*
* This method returns the int value of the week day based on the string
* supplied. Please note valid week day strings are the full week day name
* or the first three letters of the week day name. For example Mondya,
* Tuesday or Mon, Tue.
*
* This method is not case sensitive.
*
*/
private static int getWeekday(String weekday) throws Exception {
if ("SUN".equalsIgnoreCase(weekday)
|| "SUNDAY".equalsIgnoreCase(weekday)) {
return Calendar.SUNDAY;
}
if ("MON".equalsIgnoreCase(weekday)
|| "MONDAY".equalsIgnoreCase(weekday)) {
return Calendar.MONDAY;
}
if ("TUE".equalsIgnoreCase(weekday)
|| "TUESDAY".equalsIgnoreCase(weekday)) {
return Calendar.TUESDAY;
}
if ("WED".equalsIgnoreCase(weekday)
|| "WEDNESDAY".equalsIgnoreCase(weekday)) {
return Calendar.WEDNESDAY;
}
if ("THU".equalsIgnoreCase(weekday)
|| "THURSDAY".equalsIgnoreCase(weekday)) {
return Calendar.THURSDAY;
}
if ("FRI".equalsIgnoreCase(weekday)
|| "FRIDAY".equalsIgnoreCase(weekday)) {
return Calendar.FRIDAY;
}
if ("SAT".equalsIgnoreCase(weekday)
|| "SATURDAY".equalsIgnoreCase(weekday)) {
return Calendar.SATURDAY;
}
throw new Exception("Day of the week cannot be :: " + weekday);
}

/*
* Throws exception stating that a particular DateFreqHolder variable cannot
* be null for a particular frequency
*
*/
private static void throwNullVarForFreqException(String var, String freq)
throws Exception {
throw new Exception("DateFreqHolder cannot have a null :: " + var
+ " when freq is :: " + freq);

}

/*
* Throws exception stating that a particular variable cannot be null.
*
*/
private static void throwNullVarException(String var) throws Exception {
throw new Exception("DateFreqHolder cannot have a null :: " + var);
}

/*
* Add a month to the supplied calender. After that set the date to the
* runDate(day of the month) supplied.
*
*/
private static Timestamp addMonth(Calendar cal, String runDate)
throws Exception {
return addMonths(cal, 1, runDate);
}

/*
* Add months to the supplied calender as per noOfMonths. After that set
* the date to the runDate(day of the month) supplied.
*
*/
private static Timestamp addMonths(Calendar cal, int noOfMonths,
String runDate) {
cal.add(Calendar.MONTH, noOfMonths);
if (RunFreqInterface.LAST_DAY_OF_MONTH.equals(runDate)
|| ((new Integer(runDate)).intValue() > cal
.getActualMaximum(Calendar.DAY_OF_MONTH))) {
cal.set(Calendar.DAY_OF_MONTH, cal
.getActualMaximum(Calendar.DAY_OF_MONTH));
} else {
cal.set(Calendar.DAY_OF_MONTH, (new Integer(runDate)).intValue());
}
return new Timestamp(cal.getTime().getTime());
}

/*
* This method is used for yearly tasks.
*
* It add months to the supplied calender as per noOfMonths which will be 12
* for a yearly task. After that it sets the month to the runMonth(month of
* the year) supplied and the runDate(day of the month) to the supplied
* runDate.
*
*/
private static Timestamp addMonths(Calendar cal, int previousRunMonth,
int runMonth, String runDate, int noOfMonths) throws Exception {
if (previousRunMonth == runMonth) {
cal.add(Calendar.MONTH, noOfMonths);
return new Timestamp(cal.getTime().getTime());
} else {
if (runMonth > previousRunMonth) {
return addMonths(cal, runMonth - previousRunMonth, runDate);
} else {
return addMonths(cal, noOfMonths
- (previousRunMonth - runMonth), runDate);
}
}
}

/*
* This method is used for quarterly tasks.
*
* It add 3 months to the supplied calender. After that it sets the
* the runDate(day of the month) to the supplied runDate.
*
*/
private static Timestamp addQuarter(Calendar cal, int previousRunMonth,
String runDate) throws Exception {
if (isQuarterMonth(previousRunMonth)) {
return addMonths(cal, 3, runDate);
} else {
return addMonths(cal,
getNoOFMonthsToNextQuarterMonth(previousRunMonth), runDate);
}
}

/*
* This method is used for quarterly tasks.
*
* It returns an int value that is used to add up the months
* for a quarter.
*
* The reason this method is needed is that all quarters are
* fixed i.e. March, June, September and December
*
* For example a date is in october, so the number of months for it
* to reach the next quarter is 2 months. How ever if a date is in november
* the number of months for it to reach the next quarter is 1 month.
*
*/
private static int getNoOFMonthsToNextQuarterMonth(int previousRunMonth)
throws Exception {
if (previousRunMonth > 12) {
throw new Exception("Month cannot be :: " + previousRunMonth);
}
if (Calendar.MARCH >= previousRunMonth) {
return Calendar.MARCH - previousRunMonth;
} else if (Calendar.JUNE >= previousRunMonth) {
return Calendar.JUNE - previousRunMonth;
} else if (Calendar.SEPTEMBER >= previousRunMonth) {
return Calendar.SEPTEMBER - previousRunMonth;
} else if (Calendar.DECEMBER >= previousRunMonth) {
return Calendar.DECEMBER - previousRunMonth;
}
return 0;
}

/*
* This method checks wether the previousRunMonth supplied is a quarter
* month.
*/
private static boolean isQuarterMonth(int previousRunMonth) {
if (Calendar.MARCH == previousRunMonth
|| Calendar.JUNE == previousRunMonth
|| Calendar.SEPTEMBER == previousRunMonth
|| Calendar.DECEMBER == previousRunMonth) {
return true;
}
return false;
}

/*
* This method adds weeks to a given calendar. Also it sets the run
* day(day of the month) as per the supplied run day.
*
*/
private static Timestamp addWeeks(Calendar cal,
int previousRunDateDayOfTheWeek, int runDay, int noOfWeeks) {
if (previousRunDateDayOfTheWeek == runDay) {
cal.add(Calendar.WEEK_OF_YEAR, noOfWeeks);
} else {
if (runDay > previousRunDateDayOfTheWeek) {
cal.add(Calendar.DAY_OF_WEEK, runDay
- previousRunDateDayOfTheWeek);
} else {
cal.add(Calendar.DAY_OF_WEEK,
7 - (previousRunDateDayOfTheWeek - runDay));
}
}
return new Timestamp(cal.getTime().getTime());
}

/*
* This method adds hours to a given calendar based on the integer value
* supplied.
*
*/
private static Timestamp addHours(Calendar cal, int i) {
cal.add(Calendar.HOUR_OF_DAY, 1);
return new Timestamp(cal.getTime().getTime());
}

/*
* This is the main test controller method
*/
public static void main(String[] s) {
try {
RunFreqGenerator.DateFreqHolder holder = (new RunFreqGenerator()).new DateFreqHolder();
holder.setNextDate(new Timestamp(System.currentTimeMillis()));
testHourAdd(holder);
testDayAdd(holder);
testWeekAdd(holder);
holder.setFirst_run_date("28");
holder.setSecond_run_date("29");
testMonthAdd(holder);
testSemiMonthlyAdd(holder);
testQuarterAdd(holder);
testYearAdd(holder);

// test for the last day of the month.
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DAY_OF_MONTH, 31);
holder.setFirst_run_date("1");
holder.setNextDate(new Timestamp(c.getTime().getTime()));

testMonthAdd(holder);
testSemiMonthlyAdd(holder);
testQuarterAdd(holder);
testYearAdd(holder);

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.MONTH, Calendar.FEBRUARY);
c1.set(Calendar.DAY_OF_MONTH, 29);
holder.setFirst_run_date("31");
holder.setNextDate(new Timestamp(c1.getTime().getTime()));

testMonthAdd(holder);
testSemiMonthlyAdd(holder);
testQuarterAdd(holder);
testYearAdd(holder);

Calendar c3 = Calendar.getInstance();
c3.set(Calendar.MONTH, Calendar.APRIL);
c3.set(Calendar.DAY_OF_MONTH, 30);
holder.setFirst_run_date("LD");
holder.setNextDate(new Timestamp(c3.getTime().getTime()));

testMonthAdd(holder);
testSemiMonthlyAdd(holder);
testQuarterAdd(holder);
testYearAdd(holder);

Calendar c4 = Calendar.getInstance();
c4.set(Calendar.MONTH, Calendar.FEBRUARY);
c4.set(Calendar.DAY_OF_MONTH, 29);
holder.setFirst_run_date("29");
holder.setNextDate(new Timestamp(c4.getTime().getTime()));
testMonthAdd(holder);
testSemiMonthlyAdd(holder);
testQuarterAdd(holder);
testYearAdd(holder);
} catch (Exception e) {
e.printStackTrace();
}

}

// the mothod names below are are self explanatory.
private static void testYear(DateFreqHolder holder, String month)
throws Exception {
System.out.println("testing Year add ::::: month :: " + month
+ " runday :: " + holder.getFirst_run_date());
holder.setFreq(RunFreqInterface.RUN_FREQ_YEARLY);
holder.setRun_month(month);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date " + month + " :: "
+ getNextDate(holder));

}

private static void testHourAdd(DateFreqHolder holder) throws Exception {
System.out.println("Testing hour add");
holder.setFreq(RunFreqInterface.RUN_FREQ_HOURLY);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date :: " + getNextDate(holder));
}

private static void testDayAdd(DateFreqHolder holder) throws Exception {
System.out.println("Testing Day add");
holder.setFreq(RunFreqInterface.RUN_FREQ_DAILY);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date :: " + getNextDate(holder));
}

private static void testWeekAdd(DateFreqHolder holder) throws Exception {

testWeekDay(holder, "SUN");
testWeekDay(holder, "MON");
testWeekDay(holder, "TUE");
testWeekDay(holder, "WED");
testWeekDay(holder, "THU");
testWeekDay(holder, "FRI");
testWeekDay(holder, "SAT");
}

private static void testWeekDay(DateFreqHolder holder, String weekDay)
throws Exception {
System.out.println("Testing Week add ::::: " + weekDay);
holder.setFreq(RunFreqInterface.RUN_FREQ_WEEKLY);
holder.setRun_day(weekDay);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date " + weekDay + " :: "
+ getNextDate(holder));
}

private static void testMonthAdd(DateFreqHolder holder) throws Exception {
System.out.println("testing month add ::::: month :: " + " runday :: "
+ holder.getFirst_run_date());
holder.setFreq(RunFreqInterface.RUN_FREQ_MONTHLY);
// holder.setRun_month(month);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date " + " :: " + getNextDate(holder));

System.out.println();
System.out.println();
System.out.println();
}

private static void testQuarterAdd(DateFreqHolder holder) throws Exception {
System.out.println("testing Quarter add ::::: " + " runday :: "
+ holder.getFirst_run_date());
holder.setFreq(RunFreqInterface.RUN_FREQ_QUARTERLY);
// holder.setRun_month(month);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date " + " :: " + getNextDate(holder));

System.out.println();
System.out.println();
System.out.println();
}

private static void testSemiMonthlyAdd(DateFreqHolder holder)
throws Exception {
System.out.println("testing Semi Monthly add ::::: "
+ " first runday :: " + holder.getFirst_run_date());
System.out.println("testing Semi Monthly add ::::: "
+ " second runday :: " + holder.getSecond_run_date());
holder.setFreq(RunFreqInterface.RUN_FREQ_SEMIMONTHLY);
// holder.setRun_month(month);
System.out.println("Previous Run date :: " + holder.getNextDate());
System.out.println("Next Run date " + " :: " + getNextDate(holder));

}

private static void testYearAdd(DateFreqHolder holder) throws Exception {
testYear(holder, "JAN");
testYear(holder, "FEB");
testYear(holder, "MAR");
testYear(holder, "APR");
testYear(holder, "MAY");
testYear(holder, "JUN");
testYear(holder, "JUL");
testYear(holder, "AUG");
testYear(holder, "SEP");
testYear(holder, "OCT");
testYear(holder, "NOV");
testYear(holder, "DEC");
System.out.println();
System.out.println();
System.out.println();
}

}