I recently tried to redesign and experiment with a database library to see if I could  add tighter Type constraints by using Generics generously- so to speak.  All was going well until I stumbled into a very peculiar issue. Java’s Generics implementation is far from perfect and there are other issues besides  the agony of runtime type erasure at times.
One of the class I was redesigning was going through a second redesign. Originally it was a simple data structure that was backed by an ArrayList which I decided to refactor to extend an ArrayList instead. Due to backward compatibility requirement I had to leave length()  and toList() method intact after getting rid of all other methods.
The refactored class looked like this after the first iteration of redesign:


public class RowSet   extends ArrayList<IRow > {

public RowSet(){
super();
}

public RowSet(Collection<IRow > rows){
super(rows);
}

public int length() {
return super.size();
}

}

IRow interface represents a database row and exposes some handy methods for getting typed database table column values  similar to the JDBC ResultSet class.
e.g. row.getDouble(column) etc.
IRow interface didn’t have Generic type parameter and I decided to add type parameter so that IRow implementation can be restricted to a certain domain object type.
e.g IRow<Address> row= new Row<Address>() etc.
After adding type parameter to IRow interface I decided to add type parameter to RowSet class as well.

Fairly straight forward.


public class RowSet<T>  extends ArrayList<IRow<T> > {

public RowSet(){
super();
}

public RowSet(Collection<IRow<T> > rows){
super(rows);
}

public int length() {
return super.size();
}

}

I started fixing up the classes referencing RowSet and IRow classes to utilize the type parameter and that’s when I stumbled into a weird problem.
The below code block was showing compile error.


Table t =  db.getTable("address");
RowSet rs=t.getRows();

for(IRow r:rs){
System.out.println(r);
}

incompatiable types
required:com.barahisolutions.database.IRow
found: java.lang.Object

and the compile error was at


for(IRow r:rs)

WTF?  Since RowSet extends ArrayList<IRow<T>, shouldn’t the item returned by the iterator in for loop be of type IRow?

I can make it play nice by adding another method to the RowSet class to return a List:

<pre>public List<IRow<T>> toList(){
return this;
}</pre>

Surely enough I can now call the getList() method in RowSet class which essentially returns the  RowSet itself as a list and iterate over it.
Here’s the code that compiles:


Table t =  db.getTable("address");
RowSet rs=t.getRows();
List<IRow> list=rs.toList();

for(IRow r:list){
System.out.println(r);
}

We  sure can get rid of the superfluous toList method and its workaround but it requires some discipline when it comes to usage.
To be able to iterate on the RowSet, the RowSet variable has to be declared with wildcard type parameter if explicit type parameter cannot be used   i.e RowSet<Person> rs  like declaration .

Table t =  db.getTable("address");
RowSet<?> rs=t.getRows();

for(IRow r:rs){
System.out.println(r);
}

Now it all plays out nice. But every time someone has to write similar code, they have to either know generics fairly well or they’ll have to spend some time figuring  out why  their code without type parameter doesn’t compile.

I love Java……..

Using Selenium for load testing isn’t considered a good practice presumably because Selenium is intended for functional testing rather than load testing and as such its not the right tool for load testing.
Just because Selenium was intended for functional and regression testing doesn’t mean that it cannot be used to aid  load testing applications with JMeter -especially if  the application under test makes heavy use of ajax.

JMeter can be used to record browser actions using proxy, but since JMeter  doesn’t handle Javascript, it cannot be  used on its own to simulate realistic user interaction with a  Javascript/Ajax  heavy web application.
JMeter does what it does very well, but there’s no reason not to make it do things even better if tools like Selenium can aid it.
Selenium can be used to record user-interaction with a web application where lots of interactions happen  using Ajax.

And its not complicated to integrate Selenium with JMeter.

Create a test project to test the generated unit test. Add Junit and Selenium Firefox Driver dependency to the project.
Example Maven dependency.

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.24.1</version>
<scope>test</scope>
</dependency>

Record user actions  using Selenium IDE and export the script as JUnit test case.
Here’s an example of a simple user interaction  where user visits a site and logs in.

 


public class LoginTest extends TestCase {

    private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();

public void setUp() throws Exception {

        driver = new HtmlUnitDriver();
baseUrl = "http://localhost:8080";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

public void testLogin() throws Exception {

driver.get(baseUrl + "/home.htm");
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("dummyuser");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("dummypwd");
driver.findElement(By.id("btnLogin")).click();
driver.findElement(By.id("label-10")).click();

}

public void tearDown() throws Exception {

driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

}

Run the unit test. Selenium will open Firefox and replay the actions previously recorded.

Now that we know the test works and we can see it working visually, change the Selenium Maven dependency from Firefox Driver to HtmlUnit Driver.
We don’t want JMeter to open hundreds of firefox browsers whe we do the actual testing so we’ll use HtmlUnit Headless browser instead.

Replace the selenium dependency added earlier with the below HtmlUnit Driver dependency.

 <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.24.1</version>
<scope>test</scope>
</dependency>

Add the following to the build->plugins node so that the project generated a jar file for our test class.


<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Run mvn install or use your favourite IDE to build the project, maven will create a jar file with junit test classes in the target folder in <PROJECT-NAME>-<VERSION>-tests.jar format.

Download JMeter if you haven’t already got a copy of it.
Download selenium-java-2.24.1.jar and selenium-server-standalone-2.24.1.jar files from Selenium download page and copy them over to lib folder in JMeter installation folder.
Copy the junit test class jar file created by maven to lib/junit folder in JMeter installation folder.

Start up JMeter and create a Test plan. Add ThreadGroup to the test plan and add Junit Request Sampler to the Thread Group from the context menu [add->Sampler->Junit Request].
The Junit Request window should display the Junit Test Class (com.bs.webtest.LoginTest ) as well as the test method (loginTest) automatically picked up by JMeter.
Now simply configure the ThreadGroup for the number of Threads(users) you want to create and configure Loop Count for number of iteration and you are ready to go.

 

 

In the previous post I presented a Visitor Pattern framework adaptation that solves the Expression Problem.
But nice as it was it has its limitations and and drawbacks which I detailed at the end of the post.
In this post I’ll explore a  Visitor pattern implementation with Object Algebras.

The solution is actually quite straight-forward adaptation of a solution presented in a paper called Extensibility for the Masses: Practical Extensibility with Object Algebras.
The paper is interesting  without veering into highly academic discussion and provides some nice examples.
I have added another layer of  abstraction to the visitor to provide a higher degree of reuse and extensibility. To achieve higher degree of reuse I have defined a  final Void class with one static method that returns a singleton
instance of the Void class. This class is merely used by visitors that aren’t interested in returning values from their visit method, the methods  in those visitors simply return an instance of Void once the code block in the method body finishes executing.  Since every visitor returns something from its visit methods it provides us with a better means of abstraction.

The pattern implementation is simple and provides static type safety ensuring that no data class can be passed to visitors unless there is an implementation for it.

I’ll start off with a simple implementation that simply contains application code and doesn’t depend on any other classes except the application specific ones.
The example is the same as the one in previous post with shapes data classes. This time the classes are pure pojo with no interface or abstract class. And the pattern doesn’t creep into the data classes as no accept methods are required.

Circle class:

public class Circle    {

private final double radius;

public Circle(double radius){
this.radius = radius;

}

/**
* @return the radius
*/
public double getRadius() {
return radius;
}

}

Rectangle class:


public class Rectangle  {
private final double height;
private final double width;

public Rectangle(double height, double width){
this.height = height;
this.width = width;
}

/**
* @return the height
*/
public double getHeight() {
return height;
}

/**
* @return the width
*/
public double getWidth() {
return width;
}

}

.

Next we’ll define an interface used for printing as the first example will use a visitor that simply prints the output to the console.
Its only method print will be called to actually print to console.

IPrint Class:


public interface Print {

public void print();
}

IShapeVisitor interface:

public interface IShapeVisitor<T> {

public T visit(Circle c);

public T visit (Rectangle r);
}

.

PrintVisitor : Implementation of IShapeVisitor interfacewith methods that return anonymous Print implementation.
The printing task is handled by the Print implelentation

public class PrintVisitor implements IShapeVisitor<Print> {

@Override
public Print visit(Circle c) {
return new Print() {

@Override
public void print() {
System.out.println("Circle");
}
};
}

@Override
public Print visit(Rectangle r) {
return new Print() {

@Override
public void print() {
System.out.println("Rectangle");
}
};
}

}
 

.

That’s all that required for the the visitor implementation. Its a clean implementation as its not pervasive and the data classes are blissfully unaware of Visitors and the implementations don’t require them to extend super classes or to implement interface.


IShapeVisitor<Print> v= new PrintVisitor();

v.visit(new Circle(10)).print();//prints out Circle.
v.visit(new Rectangle(10, 10)).print();//prints out Rectangle

.

Subclassing Test:Data Extensibility test
We now need to confirm that adding new data doesn’t require any source-level extension and can be handled without modifying the existing classes.

Triangle class:


public class Triangle  {

private final double height;
private final double base;

public Triangle(double height, double base){
this.height = height;
this.base = base;
}

/**
* @return the height
*/
public double getHeight() {
return height;
}

/**
* @return the width
*/
public double getBase() {
return base;
}
}

.

Now we need to define an interface for handling the new Triangle class.

ITriangleExtendedVisitor interface:


public interface ITriangleExtendedVisitor<T>  extends IShapeVisitor<T>{

public T visit(Triangle t);

}

.

TriangleExtendedPrintVisitor class: trivial implementation of ITriangleExtendedVisitor.


public class TriangleExtendedPrintVisitor  extends PrintVisitor implements ITriangleExtendedVisitor<Print> {

@Override
public Print visit(Triangle t) {
return new Print() {

@Override
public void print() {
System.out.println("Triangle");
}
};
}

}

.

Test code:


ITriangleExtendedVisitor pv = new TriangleExtendedPrintVisitor();

pv.visit(new Circle(10)).print();//prints Circle
pv.visit(new Rectangle(10, 10)).print();//prints Rectangle
pv.visit(new Triangle(10, 10)).print();//prints Triangle

.

With that test passing, we can safely say that the visitor approach promises us data extensibility without the need to make source code changes.

Operation Extensibility test:
To test the other side of the coin, we’ll implement a visitor to calculate area of the shapes.
Before we define the visitor we need to define an interface similar to Print that with a method that returns a double value this instead of void.
The calculation will be performed in its method body and the calling code need to call the method to obtain the area value.

AreaCalculator interface:


public interface AreaCaclulator {

public double calculate();
}

.

With that interface defined we have got all the necessary ingredients to whip up a AreaVisitor.
I have directly defined a concrete class rather than using an interface to keep things small.

AreaVisitor class:


public class AreaVisitor implements ITriangleExtendedVisitor<AreaCaclulator> {

@Override
public AreaCaclulator visit(final Triangle t) {
return new AreaCaclulator() {

@Override
public double calculate() {
return t.getBase()*t.getHeight()/2;
}
};
}

@Override
public AreaCaclulator visit(final Circle c) {
return new AreaCaclulator() {

@Override
public double calculate() {
return Math.PI * (Math.pow(c.getRadius(), 2.0));
}
};
}

@Override
public AreaCaclulator visit(final Rectangle r) {
return new AreaCaclulator() {

@Override
public double calculate() {
return r.getHeight()*r.getWidth();
}
};
}

}

.

As with the PrintVisitor the visit method returns an anonymous class with one method and this time its a value returning methods which gives us the area of the Shapes we are interested in.

Unit Test:


AreaVisitor av = new AreaVisitor();

assertEquals(78.5, av.visit(new Circle(5)).calculate(),0.1);
assertEquals(100, av.visit(new Rectangle(10, 10)).calculate(),0.001);
assertEquals(50, av.visit(new Triangle(10, 10)).calculate(),0.001);

.

With that test passing we can be assured that the visitor pattern implementation with Object Algebras solves the expression problem and gives us an implementation allowing data and operation extensibility
without requiring any change in the source code. As with the previous example suing Visitor framework it provides object-level extensibility as old object will continue to work if the new implementations are added to a running system.

But, that doesn’t necessarily mean that the implementation we have is the cleanest one robust enough to handle various types of visitors. We have had to define two separate interfaces for handling the actual
printing and for actual area calculation. Which means that every-time we add a new visitor chances are we’ll have to add a new interface along with Visitor implementation.

The problem with Visitors is that a visitor may be either required to return an interface that provides computes and returns a value or it might just perform some side-effect and have no return value.
We cannot define a single interface to cater for both requirements as with one the method in the interface implementation will have a return value, where as the one performing side-effect will
have a void method signature.
The only way we can abstract away both the requirements is by modelling the void as a data type that has no property and no operation. So any method that isn’t interesting in returning value will simple return a
singleton instance of a Void data type.Its essentially a Java equivalent functional programming’s Unit type. We aren’t using the Void class provided by JVM because it cannot be instantiated and programmers will always
have to remember to pass in null.

Void class:


public final class Void {

private static final Void instance= new Void();

private Void(){}

public static Void Void(){
 return instance;
 }

}

.

We can now define a generic value returning interface that can be used by all visitor without each visitor having to define one -which is essentially poor-man’s higher order function.

IValue interface: It has one method get that returns computes and returns value which is a parametrized type.


public interface IValue<T> {

public T get();

}

We’ll use the IValue interface as return type of all visit methods in our visitor interface definition.

IShapeVisitor interface:


public interface IShapeVisitor<T> {

public IValue<T> visit(final Circle c);

public IValue<T> visit (final Rectangle r);
}

.

We’ll again start off with a visitor that prints the name of a shape data object to console.
We can actually make the visitor return a value and print that value to console outside of the implementation, but we won’t do that just to make it as a test case for
operations that don’t return a value- e.g database write, file write, logging.


import static object.algebra.strategy.Void.*;

public class PrintVisitor implements IShapeVisitor<Void> {

@Override
public IValue<Void> visit(final Circle c) {
return new IValue<Void>() {

@Override
public Void get() {
System.out.println("Circle");
return Void();
}
};
}

@Override
public IValue<Void> visit(final Rectangle r) {

return new IValue<Void>() {

@Override
public Void get() {
System.out.println("Rectangle");
return Void();
}
};
}

}

.

I have used static import on Void class to use its static Void method that return a singleton instance of Void class.Although it looks like a constructor call without new keyword, that’s not the case
and since lowercase void is a keyword in Java I can’t define a void method so have to resort to Void instead.

Subclassing Test:Data Extensibility test

Triangle print visitor interface and implementation:


public interface ITriangleExtendedVisitor<T>  extends IShapeVisitor<T>{

public IValue<T> visit(Triangle t);

}

public class TriangleExtendedPrintVisitor  extends PrintVisitor implements ITriangleExtendedVisitor<Void> {

@Override
public IValue<Void> visit(Triangle t) {
return new IValue<Void>() {

@Override
public Void get() {
System.out.println("Triangle");
return Void();
}
};
}

}

.

In the Visitor framework in the previous post the framework failed to dispatch to the right visitor if a data class was sub-classed, the visit method for its super-class was always called instead.
Overcoming that might be possible but I didn’t dig into it because the framework was going to get over-complicated when accommodating such behavior. But with this implementation there’s no such problem
because visitor methods are statically type checked and the correct method is executed no matter what hierarchy of sub classing for data class is.
To demonstrate we’ll add a Square class to the mix and provide a visitor extension for it.


public class Square extends Rectangle{

public Square(double side){
super(side, side);
}
}

.

Visitor interface extension and implementation for Square sub class.


public interface ISquareExtendedVisitor<T>  extends ITriangleExtendedVisitor<T> {

public IValue<T> visit(final Square t);

}

&nbsp;

public class SquareExtendedPrintVisitor  extends TriangleExtendedPrintVisitor implements ISquareExtendedVisitor<Void> {

@Override
public IValue<Void> visit(final Square t) {
return new IValue<Void>() {

@Override
public Void get() {
System.out.println("Square");
return Void();
}
};
}

}

.

Litmus test:


ISquareExtendedVisitor<Void>  pv = new SquareExtendedPrintVisitor  ();

pv.visit(circle).get();//prints circle
pv.visit(rectangle).get();//prints  Rectangle
pv.visit(triangle).get();//prints Triangle
pv.visit(square).get();//prints Square

.

The Visitor correctly dispatches the method for printing Square.

That provides the proof that the implementation has no problem with data extensibility and goes half-way toward solving the expression problem.


Operation Extensibility test:
We again add Area calculating visitor implementation.

public class AreaVisitor implements ISquareExtendedVisitor<Double> {

@Override
public IValue<Double> visit(final Triangle t) {
return new IValue<Double>() {

@Override
public Double get() {
return t.getBase()*t.getHeight()/2;
}
};
}

@Override
public IValue<Double> visit(final Circle c) {
return new IValue<Double>() {

@Override
public Double get() {
return Math.PI * (Math.pow(c.getRadius(), 2.0));
}
};
}

@Override
public IValue<Double> visit(final Rectangle r) {
return new IValue<Double>() {

@Override
public Double get() {
return r.getHeight()*r.getWidth();
}
};
}

@Override
public IValue<Double> visit(final Square s) {
return new IValue<Double>() {

@Override
public Double get() {
return s.getHeight()*s.getWidth();
}
};
}

}

.

Test for operation extensibility:


AreaVisitor av = new AreaVisitor();

assertEquals(78.5, av.visit(new Circle(5)).get(), 0.1);
assertEquals(100, av.visit(new Rectangle(10, 10)).get(), 0.001);
assertEquals(50, av.visit(new Triangle(10, 10)).get(), 0.001);
assertEquals(25, av.visit(new Square(5)).get(), 0.001);

.

The passing of the test proves that visitor pattern implementation with Object Algebras provides the flexibility for data as well as operation extension and doesn’t depend on any framework or tool

for it to work properly.  It also provides perhaps the cleanest and most straight-forward implementation for tackling the ‘Expression Problem‘ and data-centric vs operation-centric duality.

Visitor pattern provides a flexible mechanism for adding operations to a set of classes. Its much better option than having to retrofit existing interface and its implementations with operations as needs arise. Retrofitting has bigger consequence if the interface api is used by 3rd party clients as their code will no longer compile after upgrade due to missing implementation for the added operation in the interface.
But Visitor pattern has its own extensibility issue. If a new subclass is added then the Visitor interfaces have to be changed to add operation for the new subclass and the implementations have to be changed to accommodates the newly added class.

There has been quite a lot of attempts to solve this dilemma of date-centric and operation-centric approach in various languages.
The solutions try to address source-level extensibility, code-level extensibility and object-level extensibility.
The most promising of those solutions I came across came in two flavors.

In this post I will explore the solution presented Mads Torgersen using a visitor framework to dispatch to correct methods on visitors and provided a default handler method to handle subclasses which hasn’t been addressd in a visitor implementation. The solution is robust and supports both data and operation extensions without having to tinker with existing code and goes a long way towards solving the expression problem.
The solution allows all three levels of extensibility.

The original solution had rather unnecessary boiler-plate and framework itself was unnecessarily creeping in the implementation classes. I have pushed all methods on Visitable classes to the framework except for the accept method and I have also pushed all framework specific methods on visitor classes to the framework so that it only needs overloaded visit methods.
More generics has been added to the original framework for type safety and extensibility.
Since the framework relies on type discovery of visitor and visited classes and due to runtime type erasure of classes in Java, I had to pinch the code written by Ian Robertson that uses reflection to find the generic type parameter class. The type discovery method is the only dependency required by the framework. Visit here for the article and code.

The framework consist of Visitor and Visitable interface and their abstract implementation that does all the heavy lifting.

Visitor Interface:


public interface Visitor {

     /**
     * The primary method used to route Visitables to their respective
     * methods in visitor implementation using double dispatch
     * via Visitable's handle method.
      * @param e data object
     */
      public void apply(Visitable e);

     /**
     * default handler where no suitable method for dispatching exist for a Visitable     *
     * @param e data object
     */
      public <V extends Visitor> void handleDefault(Visitable e);
}

.
.

Visitable interface. The interface implemented by data classes through Abstract class.


public interface Visitable {

    /**
     * The primary method used to route Visitables to their respective
     * methods in visitor implementation using double dispatch
     * via Visitable's handle method.
      * @param e data object
     */
    public < V extends Visitor > void handle(V v);
}

.
.

AbstractVisitor class: Abstract class used to delegate Visitables to the correct method using triple-dispatch.

public abstract class AbstractVisitor implements Visitor {

    /**
     *  {@inheritDoc }
    */
    @Override
    public final  void apply(Visitable e) {
            e.handle(this);
    }

    /**
     *  {@inheritDoc }
    */
    @Override
    public final void handleDefault(Visitable e) {
        throw new UnsupportedOperationException("No Suitable method to handle Visitable[" + e.getClass().getSimpleName() + "].  ");
    }
}

.
.

AbstractVisitable class: This class does the heavy lifting with some help from reflection. Reflection is used for type discovery of Visitor implementations.
If a Visitor is deemed to have a suitable method then its passed to the accept method of concrete implementation which knows which method on a visitor to
call.
ClassUtil‘s getTypeArguments method is used for runtime generic type discovery of V parameter that extends Visitor.
Copy getTypeArguments and getClass method from the site and stick it to a Util class or you can put it in the AbstractVisitor class for simplicity.


public abstract class AbstractVisitable < V extends Visitor >
 implements Visitable {

    private final Class clazz;

    public AbstractVisitable() {
        clazz = (Class) ClassUtil.getTypeArguments(AbstractVisitable.class, getClass()).get(0);
    }

    /**
     * method to check if the visitor passed in is the required type.
     *
     * @param v
     * @return
     */
    private boolean canAccept(Visitor v) {
        return clazz.isAssignableFrom(v.getClass());

    }

    /**
     * {@inheritDoc }
     */
    public final void handle(Visitor v) {
        if (canAccept(v)) {
            accept(clazz.cast(v));
        } else {
            v.handleDefault(this);
        }
    }

    /**
     * Methods concrete Visitable class need to implement. This is where the
     * actual dispatch to the correct Visitor method need to be done. The
     * implementation is just a boiler-plate and should contain v.visit(this)
     * call;
     *
     * @param v
     */
    public abstract void accept(V v);
}

.
.

Those four classes are what drives the Visitor framework and what makes it work.

I will use some trivial Shape classes to test the framework and validate it. I’ll initially start off with just two Shapes-Rectangle and Circle.
I’ll use a visitor that simply prints the type of the shape to the console.

Shape: A marker interface to group all the shapes under.


public interface Shape  extends Visitable{

}

.
.

Circle Class:


public class Circle  extends AbstractVisitable < ShapeVisitor > implements Shape  {

    private final double radius;

    public Circle(double radius){
        this.radius = radius;
    }

    /**
     * @return the radius
     */
    public double getRadius() {
        return radius;
    }

       @Override
    public void accept(ShapeVisitor v) {
        v.visit(this);
    }

}

.
.

Rectangle Class:


public class Rectangle  extends AbstractVisitable < ShapeVisitor >  implements Shape {

    private final double height;
    private final double width;

    public Rectangle(double height, double width){
        this.height = height;
        this.width = width;
    }

    /**
     * @return the height
     */
    public double getHeight() {
        return height;
    }

    /**
     * @return the width
     */
    public double getWidth() {
        return width;
    }

        @Override
    public void accept(ShapeVisitor v) {
        v.visit(this);
    }

}

.
.

ShapeVisitor: The interface with visit methods specific to Circle and Rectangle objects.


public interface  ShapeVisitor extends Visitor  {

    public  void visit(Rectangle rectangle) ;

    public  void visit(Circle circle) ;

}

.
.

PrintVisitor: Visitor that simply prints the name of Visitable object Class to the console


public class PrintVisitor extends AbstractVisitor implements ShapeVisitor {

    @Override
    public void visit(Rectangle rectangle) {
        System.out.println("Rectangle");
    }

    @Override
    public void visit(Circle circle) {
        System.out.println("Circle");
    }

}

.

Here’s some sample test code.


       ShapeVisitor v= new PrintVisitor();
       Shape c= new Circle(5);
       v.apply(c);// prints Circle

       Shape r= new Rectangle(5, 5);
       v.apply(r); //prints Rectangle

.

Now that the basic framework has been tested out, its time to test its extensibility.

.
.

Subclassing Test: Data Extensibility test
Ability to add Data Class without the need to change source code while maintaining object level extensibility.

We’ll add a Triangle class to the mix first.


public class Triangle  extends AbstractVisitable < ITriangleExtendedVisitor >  implements Shape {
    private final double height;
    private final double base;

    public Triangle(double height, double base){
        this.height = height;
        this.base = base;
    }

    /**
     * @return the height
     */
    public double getHeight() {
        return height;
    }

    /**
     * @return the width
     */
    public double getBase() {
        return base;
    }

    @Override
    public void accept(ITriangleExtendedVisitor v) {
        v.visit(this);

    }

}

.
.

Adding data class requires a Visitor implementation to be created to handle the new data class. Otherwise there’s no point in adding a new data class.
The ITriangleExtendedVisitor interface used in the accept method needs to be defined.


public interface ITriangleExtendedVisitor extends ShapeVisitor {

    public void visit(Triangle t);

}

Now let’s test it :


 ShapeVisitor v= new PrintVisitor();

 Shape t = new Triangle(12, 11);
       v.apply(t); // throws java.lang.UnsupportedOperationException: No Suitable method to handle Visitable[Triangle].

.
.

The test failed because PrintVisitor class used doesn’t have a suitable method to handle Triangle class.
Let’s implement a Visitor to provide handling for Triangle class.


public class TriangleExtendedPrintVisitor extends PrintVisitor implements ITriangleExtendedVisitor{

    @Override
    public void visit(Triangle t) {
        System.out.println(" Triangle");
    }

}

.

Its very important to keep track of the latest implementation of Visitor and to ensure that the new Visitor class extends the latest implementation.
In our case we only have one PrintVisitor class as yet and as such we can extend that to create the new visitor to handle Triangle class.

Testing time:

 ShapeVisitor v= new TrianglePrintVisitor();

       Shape t = new Triangle(12, 11);
       v.apply(t);// prints Triangle

Shape c= new Circle(5);
       v.apply(c);//prints Circle

.

Data Extensibility test has passed with flying color- at least so it seems for now.

.
.

Operation Extensibility test:
Ability to add new operation to data without the need to change source code.

To test operation extensibility I’ll add a trivial Visitor to calculate area of Shape. This visitor differs from PrintVisitor in that
it needs to keep a state of the calculated area. Although this can be rectified by making the accept method in Visitable as well
as visit method in Visitor return a value, but that creates an issue for visitors that doesn’t require to return a value like the PrintVisitor.
A Void marker class can be defined to use when the return value is of no interest, but we’ll keep it simple and use state in Visitor for now.

IAreaVisitor interface makes use of the existing definition of ITriangleExtendedPrintVisitor


public interface IAreaVisitor extends ITriangleExtendedPrintVisitor{

    Double getResult();

}

.
.

The concrete implementation


public class AreaVisitor extends AbstractVisitor implements IAreaVisitor {

    double result=0.0;

      public void visit(Rectangle rectangle) {
         result= rectangle.getHeight() * rectangle.getWidth();
    }

    public void visit(Circle circle) {
         result= Math.PI * (Math.pow(circle.getRadius(), 2.0));
    }

    @Override
    public void visit(Triangle t) {
         result=t.getBase()*t.getHeight()/2;
    }

     @Override
    public Double getResult() {
        return result;
    }
}

.
.

Testing time again:


IAreaVisitor v= new AreaVisitor();

       Shape c= new Circle(5);
       v.apply(c);
       assertEquals(78.5, v.getResult(),0.1);

       Shape r= new Rectangle(5, 5);
       v.apply(r);
       assertEquals(25, v.getResult(),0.1);

       Shape t = new Triangle(10, 10);
       v.apply(t);
        assertEquals(50, v.getResult(),0.1);

.
.

Operation extension poses no problem as that’s the real strength of Visitor pattern.
With both operation and data extensibility this framework is a good solution to the expression problem.

The drawback of this solution is the lack of static type checking on data classes which means that a visitable object which doesn’t yet have implementation for it in a visitor can be passed in causing it to raise runtime exception. It also requires programmers to be disciplined when extending visitors to ensure that the latest version of a visitor is extended.
If another Shape is to be added and a visitor interface needs to be defined to extend ITriangleExtendedVisitor. IF by mistake ShapeVisitor interface is extended, the implementation will not be able to handle Triangle as ShapeVisitor was created when Triangle wasn’t in the scope and as such has no method for handling Triangle.

Another issue is that if you subclass a data class that has already got operation defined in a visitor, and extend the visitor to provide implementation for the new subclass, the framework fails to dispatch the subclass to the correct visitor method.

If we define a Square that extends Rectangle, and pass the Square to a Visitor that has method to handle Square, it will be dispatched to the method implemented to handle Rectangle.

public class Square  extends Rectangle {

    public Square(double side){
        super(side,side);
    }

}

.
.

If we have an interface ISquareExtendedVisitor with the required method definition and create SquareExtendedPrintVisitor concrete class and use, the framework won’t dispatch to the
visit(Square s) method in the Visitor implementation.

The reason for this is because the accept method in Rectangle has ShapeVisitor as parameter and not ISquareExtendedVisitor and ShapeVisitor was created when Square wasn’t in scope and as such has no implementation for handling Square.

We can use Generics to overcome this issue but there’s a price to pay.
Suppose we changed all the Shape classes to accept a type parameter

Here’s an example implementation of rectangle and the Square using type parameter

public class Rectangle <T extends ShapeVisitor>  extends AbstractVisitable<T> implements Shape  {

..............

     @Override
    public void accept(T  v) {
        v.visit(this);
    }

}

public class Square  extends Rectangle {
........
}

.
.
The above change will ensure that the correct implementation to handle Square will be used. But the problem is the framework will no longer work.
The current utility method for generic type discovery fails to discover the type parameter of AbstractVisitable extension in Rectangle class. Runtime Generic Type parameter information is only available for anonymous or Abstract class and not for concrete class. There might be a way to dig it out using gentyref library for runtime Generic information using reflection ,but I haven’t tried it. And besides as soon as you have to include a whole library for a simple Visitor framework to work, then it might be time to find another solution.
Which is where the second solution comes in.
The second solution is covered in my next post.

Most of circular Queue implementations I have found keep track of the head and tail of queue. Adding and removing items are done using head and tail pointers.
I decided to implement a circular queue my using modulo operation to figure head and tail instead of defining head and tail pointer variables.
The queue class also implements Iterable so that the usual ‘for’ comprehension can be used to iterate through the queue.

The queue is backed by ArrayList and as such its not thread-safe.

Although in reality queue class should only expose enqueue(),dequeue(),size() and isEmpty() methods to keep the API clean , I implementation has extra methods to provide
list operations.
Although allowing index based access may not really be that useful since item indexes will be rotated when items overwrite existing items, I couldn’t help but over-engineer the queue :-)

here’s the iterable circular queue implementation:


public class IterableCircularQueue<T> implements Iterable<T> {

    private final int capacity;
    private List<T> list;
    private int count = 0;

    public IterableCircularQueue(int capacity) {
        this.capacity = capacity;
        list = new ArrayList<T>(capacity);

    }

    /**
     * add item to queue
     * @param elem
     */
    public void enqueue(T elem) {

        if (count < capacity) {
            list.add(elem);
        } else {
            if (list.size() == capacity) {
                list.set(count % capacity, elem);
            } else {
                list.add(count % capacity, elem);
            }
        }
        count++;

    }

    /**
     * Inspect the first item of the queue.
     * @return
     */
    public T peek() {

        if (list.isEmpty()) {
            throw new RuntimeException(" queue is empty");
        }
        T value = null;
        if (count > capacity) {
            int head = count % capacity;
            if (head >= list.size()) {
                head = head - list.size();
            }
            value = list.get(head);
        } else {
            value = list.get(0);
        }

        return value;
    }

    /**
     * remove an item from the queue
     * @return
     */
    public T dequeue() {

        if (list.isEmpty()) {
           throw new RuntimeException(" queue is empty");
        }
        T value = null;
        if (count > capacity) {
            int head = count % capacity;
            if (head >= list.size()) {
                head = head - list.size();
            }
            value = list.remove(head);
        } else {
            value = list.remove(0);
        }
        if (list.isEmpty()) {
            count = 0;
        }

        return value;
    }

    /**
     * index-based access to items in queue.
     * @note The item won't be removed when accessed using index
     * @param index
     * @return
     */
    public T get(int index) {

        if (index < 0 || index >= list.size()) {
            throw new IndexOutOfBoundsException();
        }

        int i = index;

        if (count > capacity) {
            i = count % capacity + index;
            if (i >= list.size()) {
                i = i - list.size();
            }
        }
        return list.get(i);
    }

    /**
     * number of items in queue
     * @return
     */
    public int size() {
        return list.size();
    }

    /**
     * check if the queue is empty
     * @return
     */
    public boolean isEmpty() {
        return list.isEmpty();
    }

    public String toString() {
        return list.toString();
    }

    /**
     * Fetch an Iterator to iterate through the queue.
     * @return
     */
    public Iterator<T> iterator() {
        return new QueueIterator();
    }

    /**
     * Queue Iterator implementation
     */
    private class QueueIterator implements Iterator<T> {

        int cursor = 0;

        public boolean hasNext() {

            if (cursor >= capacity) {
                return false;
            }

            try {
                return get(cursor) != null;
            } catch (Exception e) {
                return false;
            }
        }

        public T next() {
            T val = get(cursor);
            cursor++;
            return val;
        }

        public void remove() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}

Test cases:


 IterableCircularQueue<Integer> q = new IterableCircularQueue(5);

        q.enqueue(0);
        q.enqueue(1);
        q.enqueue(2);
        q.enqueue(3);
        q.enqueue(4);

        assertEquals(new Integer(4), q.get(4));

        q.enqueue(5);// first item gets over-written

        assertEquals(new Integer(5), q.get(4));
         assertEquals(new Integer(1), q.dequeue());

        q.enqueue(6);
        q.enqueue(7);

        assertEquals(new Integer(3), q.dequeue());

        assertEquals(new Integer(5), q.get(1));
        assertEquals(new Integer(6), q.get(2));

        q.enqueue(8);
        q.enqueue(9);

        assertEquals(new Integer(6), q.get(1));
        assertEquals(new Integer(5), q.dequeue());
        assertEquals(new Integer(7), q.get(1));
        assertEquals(new Integer(6), q.dequeue());
        assertEquals(new Integer(8), q.get(1));

         assertEquals(new Integer(7), q.peek());

        assertEquals(new Integer(7), q.dequeue());
        assertEquals(new Integer(8), q.dequeue());
        assertEquals(new Integer(9), q.dequeue());

        assertTrue( q.isEmpty());

        q.enqueue(10);
        q.enqueue(11);
        q.enqueue(12);
        q.enqueue(13);

        assertEquals(new Integer(10), q.get(0));

        q.enqueue(14);
        q.enqueue(15);
        q.enqueue(16);
        q.enqueue(17);

        assertEquals(new Integer(13), q.get(0));
        assertEquals(new Integer(13), q.peek());
        assertEquals(new Integer(13), q.dequeue());
        assertEquals(new Integer(14), q.get(0));

        System.out.println(q);//prints [15,16,17,14]

        for (Integer i : q) {
            System.out.println(i + " "); //prints 14 15 16 17
        }

One of the issues when I write unit test is having to create TestSuite after TestSuite at package level to run all the test in a package or run all tests in a project. And I really dislike the repetitiveness of it.
And sometimes I just like to test all classes in a package and its sub packages rather than running all the tests in a project due to the amount of time it takes to setup all the necessary resources.
Finally I decided to do something about it and started digging into JUnit to figure out a way to automate testing classes in a package without having to add test classes to a TestSuite.
The initial version of Suite I developed added all classes from the package a class was marked with RunWith annotation as well as all classes from sub-packages recursively.
It was all great. I could just mark a class with @RunWith(DynamicSuite.class) annotation at the root of a project’s root package and it would
run all the tests for the project. Or I could mark a class in a package with @RunWith(DynamicSuite.class) annotation and I could test just the classes in the package and its sub-packages.All sweet.
But later in some cases I only wanted to run classes in a package and not all classes in its sub-packages as well due to the speed of test as some tests in sub-packages were resource intensive. So I had to come up with a finer-grained test Suite mechanism.

To tackle that issue, I decided to add an Annotation -@NonRecursive – that marked a Test entry point ( class marked with @RunWith(DynamicSuite.class) annotation as being non-recursive.
I wanted to be able to test just a package when I wanted to without testing sub-packages, but I also wanted a over-riding mechanism to be able to run all tests in a project or a package and its sub-package such that if the entry point class is not marked as @NonRecursive , all the @NonRecursive annotaitons get ignored in subsequent sub-packages and all classes in the package and below get executed.

Here’s the DynamicSuite Class code.

/**
 *TestSuite execute all test classes from the package of  <br>
 * classes that are annotated to run with this class<br>
 * It loads all classes in the same package as the setup class and
 * loads classes from sub packages recursively.
 * If a sub-package contains a class that's marked to be run with this class<br>
 * it only loads that class so that the marked class can in turn load and execute<br>
 * test classes in its package and its subpackages.<br><br>
 * To cut it short: This class loads and executes all test classes in its package and its
 * subpackages recursively.<br<br>
 * Example usage:Just create an empty class and add <code>@RunWith</code> annotation<br>
 *
 *  <code>@RunWith(DynamicSuite.class)<br>
 * public class BatchTest {<br>
 * //no methods or body needed.<br>
 * }</code>
 * <br><br>
 * To test only classes in a package and ignore test classes in subpackages mark the class with @NonRecursive.
 * To test all test classes in a project mark a class at a project's  root test  package  with <code>@RunWith(DynamicSuite.class)</code>
 * and it will run all test classes in the project.
 * The only catch so far is that all the methods of all test classes gets run under
 * this the setup class and the results are all grouped under that class , at least from what I can see in Netbeans.
 *
 *
 * @author anjan
 */
public class DynamicSuite extends Suite {

    static boolean isEntrySuite=true;
    public DynamicSuite(Class<?> setupClass) throws InitializationError {

        super(setupClass, getTestClasses(setupClass,setupClass.isAnnotationPresent(NonRecursive.class)));

            //this will run after the initial setup has been done;
            //If a  Class is marked as NonRecursive and its the entry point of tests
            // it won't load test classes from subpackages.
            //but if the Class is marked as NonRecursive and its not the entry point
           // of tests the annotation will be ignored and all classes from subpackages of the containing
          //package will be loaded
            isEntrySuite=false;

    }

    public static Class<?>[] getTestClasses(Class setupClass ,boolean nonRecursive) {

        List<Class> classes = null;

        String packageName = setupClass.getPackage().getName();
        String path = setupClass.getProtectionDomain().getCodeSource().getLocation().getFile();
        path = path + packageName.replace('.', File.separatorChar);

        File dir = new File(path);

        try {
            classes = findTestClasses(dir, setupClass,nonRecursive);
        } catch (Exception ex) {
            throw new RuntimeException("Problem loading classes from package[" + packageName + "]", ex);
        }
        return classes.toArray(new Class[classes.size()]);
    }

    /**
     * recursively finds Classes in test package <br>
     * if it finds a class annotated with @RubWith(DynamicSuite.class)
     * if loads that class and ignores all classes and sub-packages in that package
     * because the loaded class is responsible for loading classes under ite hierarchy
     * @param dir   The root directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private static List<Class> findTestClasses(File dir, Class setupClass, boolean nonRecursive) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!dir.exists()) {
            return classes;
        }
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
               //only load classes in subpackage if the setup class isn't marked as NonRecursive
                // or its marked as NonRecursive but its not the entry point class
                if(!nonRecursive ||(nonRecursive && !isEntrySuite))
                classes.addAll(findTestClasses(file, setupClass,nonRecursive));
            }
            else if (file.getName().endsWith(".class")) {

                String className = file.getName().substring(0, file.getName().length() - 6);

                if (!className.equals(DynamicSuite.class.getSimpleName())) {

                    String packageDirPath = file.getPath();
                    packageDirPath = packageDirPath.substring(packageDirPath.indexOf("classes"));
                    String pkg = packageDirPath.replace(File.separatorChar, '.').substring(8).replace("." + file.getName(), "");
                    Class cls = Class.forName(pkg + '.' + className);
                    if (cls.isAnnotationPresent(RunWith.class)) {
                        RunWith ann = (RunWith) cls.getAnnotation(RunWith.class);

                        if (ann.value().equals(DynamicSuite.class)) {
                           //ignore the class being run, otherwise the program will crash with StackOverflowError
                            if (!cls.equals(setupClass)) {
                                classes = new ArrayList<Class>();
                                classes.add(cls);
                                break;
                            }
                        } else {
                            classes.add(cls);
                        }

                    } else {
                        classes.add(cls);
                    }

                }
            }
        }

        return classes;
    }

}

The Annotation class:

/**
 *Used to Mark DynamicSuite as NonRecursive so that:<br>
 * If a Suite that's being run is marked as NonRecursive, it will only run classes<br>
 * within the same package.<br>
 * But If the  Suite being run is not marked as  NonRecursive,<br>
 * it ignores all NonRecursive annotations in Suites contained in subpackages of the package the<br>
 * Suite class belongs to.<br>
 * The rationale is to be able to test only Tests in a package when desired at the same time<br>
 * being able to test all tests in a project or in a package and subpackages when running when the Suite being run is<br>
 * not marked as NonRecursive.<br>
 * @author anjan
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface NonRecursive {

}

Sample code:
Running all test classes recursively

@RunWith(DynamicSuite.class)
public class EntryPoint {

}

Sample code:
Running only test classes in a package

@NonRecursive
@RunWith(DynamicSuite.class)
public class EntryPoint {

}

Before Google provided HTTP reverse-geocoding service, the world was a dark place if you needed reverse-geocoding in your application.
The only way to perform reverse-geocoding was using javascript API that too using third party library.
Since the application I was working on a year or so back required reverse-geocoding- worse it was central to our geo-location based reporting – I had to find a
way of reverse geocoding high volume longitude/latitude pairs on the server side.
After contemplating various solutions/non-solutions I decided to give myself some time to come up with a solution that didn’t
require us to pay for premium service or ditch googlemaps altogether.
That’s when I came across HtmlUnit. As soon as I read about its capabilities, I suddenly had a brilliant idea!
The idea was to use HtmlUnit to access a page with a small googlemap loaded ( reverse geocoding using GDirection required an instance of googlemap to be present)
on it, that has a form for entering longitude and latitude, a button to submit reverse-geocoding request and a DIV element for populating reverse-geocoded address response
from Google.

Javascript code:

  // GMap2 object
            var map;
            // GReverseGeocoder object
            var rg;
            // text input fields
            var lat;
            var lng;
            // result div
            var addressText;

            function load() {
                if (GBrowserIsCompatible()) {
                    lat = document.getElementById("lat");
                    lng = document.getElementById("lng");
                    addressText = document.getElementById("address");

                    map = new GMap2(document.getElementById("map"));
                    map.setCenter(new GLatLng(-33.83955, 151.2084), 15);
                    map.addControl(new GLargeMapControl());
                    rg = new GReverseGeocoder(map);

                    // add listner for the result
                    GEvent.addListener(rg, "load", function(response){
                        addressText.innerHTML=response.address
                    });
                    //add listener for error response
                    GEvent.addListener(rg, "error", function(lastpoint){
                        addressText.innerHTML = "ERROR:point " + lastpoint;
                    });

                    // Listener to detect clicks on map to get coordinates to fill in the lat and lng fields-for testing purpose.
                    GEvent.addListener(map, "click", function(marker, point){
                        lat.value=point.lat();
                        lng.value=point.lng();
                    });

                }  

            }

            // get the input form lat and lng fields and issue a reverse geocode
            // request
            function reverse(){
                var point = new GLatLng(lat.value,lng.value);
                rg.reverseGeocode(point);
                return false;
            }

HTML code:

 <form name="rev" id="rev"  action="" method="post"  onSubmit=" reverse();return false;">
            <table>
                <tr><td>Latitude (WGS84)</td><td><input id="lat" name="lat" type="text" size="20" value='' /></td></tr>
                <tr><td>Longitude (WGS84)</td><td><input id="lng" name="lng" type="text" size="20" value='' /></td></tr>
                <tr><td><input name="submit" id="submit" type="submit" onClick="reverse()" value="Get Address"></td><td> address:<div id="address"></div></td></tr>

                <tr><td colspan="2"><div id="map" style="width:400px; height:400px;"></div></td></tr>
            </table>

        </form>

I wrote a Java method which accessed the webpage, populated longitude/latitude textbox in the webpage, clicked the submit button, and wait for the response
to be populated in the div element -all done using HtmlUnit’s headless browser. After sleeping for 2 seconds the method then read the content of the address div element.
And it worked flawlessly.

Java Code:

public static String latLngToAddress(Float lat, Float lon) {

        try {
            WebClient wc = new WebClient();
            wc.setThrowExceptionOnScriptError(false);

            HtmlPage page = (HtmlPage) wc.getPage("http://localhost:8084/ReverseGeocoder/");

            HtmlForm form = page.getFormByName("rev");
            HtmlInput latInput = (HtmlTextInput) form.getInputByName("lat");
            latInput .setValueAttribute(lat.toString());

            HtmlTextInput lngInput = (HtmlTextInput) form.getInputByName("lng");
            lngInput.setValueAttribute(lon.toString());

            HtmlSubmitInput button = (HtmlSubmitInput) form.getInputByName("submit");
            button.click();

            Thread.sleep(2000);

            return page.getElementById("address").getTextContent();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

I spent quite a bit of time then to finally come up with this solution. But before I finished the application, Google finally provided HTTP reverse-geocoding service which meant that there was
no need to use my solution. But at least I’m glad I tried it and came up with a solution when none existed :-)

I use a custom very lightweight persistence library that does lazy loading using CGLIB Enhanced proxy.
THe generated proxy for domain objects use Key/value Map data fed to it via a static factory method.
When a get or set method is called for the wrapped domain, the proxy check the value for the field in the Map,
if it finds an entry for the field, which means the field hasn’t been initialised, it sets the field value from Map and removes
the entry from the Map.
If no entry is found in the Map, the method returns value of the field of the domain object encapsulated by the getter method
rather than getting it from the Map.

Of course if the field is a domain object, then the object is fetched using the PK value in the Map.
That gives me the same lazy loading voodoo magic like Hibernate- the 10 pound gorrila.
The persistence is backed by a cache which looks at a domain’s metadata and
only caches those that are specified as cacheable.

Everything works like a charm except that the CGLIB enhanced objects don’t play nice with XStream at all.
When serializing enhanced objects XStream spits out gory details of classe/superclasses/interfaces and full dissection of a Map that is fed to a static method when creating the proxy object, when all i want is the pojo object wrapped by the proxy.

I believe the XStream library simply gets the value of the field rather than calling the getter method using reflection when serializing.
That must be the reason that in my case all serialised objects have empty values for fields because the fields don’t get set when the proxy is
created, they get set only setter method is called on it or getter method is called for the first time .
I think that’s the same problem with Hibernate and I guess that’s the reason it throws Lazy Initilization Exception.

I tried the CGLIBEnhancedConverter that comes with the library but it didn’t work for me.
I couldn’t find a simple enough solution in the internet and the ones I found were all Hibernate specific.
Since this is the second time I had been trying to solve the issue, I decided to push forward and find a work around myself.

After trying out a few different solutions I finally came up with a dead simple solution.
IT involves a static method to deproxy the enhanced domain objects and a XStream custom converter class.
There may be performance cost as it uses reflection eventhough getter setter methods for domain classes are cached for reuse.

Here’s the simplified method.


  /**
     * Deproxies a CGLIB enhanced proxy object
     * @param <T>
     * @param proxy
     * @return deproxied domain object
     */
    public static <T > T deproxyReflection(final T proxy) {

      Class entityClass = proxy.getClass().getSuperclass();

        T entity = (T) ClassUtil.getInstance(entityClass);

        Field[] fields =  entityClass.getDeclaredFields();

        for (Field f : fields) {
            try {

	 // no need to set the values of collections as they won;t be serialized.
                //we just need the actaul properties taht amp to table columns
                if(List.class.isAssignableFrom(f.getType()))
                    continue;

                //I use a utility method to fetch getter/setter methods.
                //it simply loops through the object and super class to find the methods.
//so instead of screwing arund with the field's security settings we'll use getters/setters to ensure its unintrusive
                Method getter = ClassUtil.getPojoMethod(entityClass, f.getName(), ClassUtil.MethodType.GETTER);
                Method setter = ClassUtil.getPojoMethod(entityClass, f.getName(), new Class[]{f.getType()}, ClassUtil.MethodType.SETTER);

                Object val = getter.invoke(proxy, null);
                setter.invoke(entity, new Object[]{val});

            } catch (Exception ex) {
                Logger.getLogger(EntityProxyFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                f.set(entity, f.get(proxy));
            } catch (Exception ex) {
                Logger.getLogger(EntityProxyFactory.class.getName()).log(Level.SEVERE, null, ex);
            } 

        }

        return entity;
    }

We need to register a converter with XStream that used the above method to sanitize the domain objects before serializing.


/**
 * XStream converter to convert a CGLIB enhanced proxy  to the wrapped pojo object.
 *
 */
public class CGLIBEnhancedEntityConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return (Enhancer.isEnhanced(clazz)  || clazz == CGLIBMapper.Marker.class) ;
    }

    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

            // deproxy before sending it off the chain for serialization. ANd that's it.
           // XStream will get a simple pojo object and it will serialize it like any other pojo object.
         context.convertAnother(EntityProxyFactory.deproxyReflection(source));

    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    throw new Error("not supported");
    }

}

And that’s it. That’s all it takes.
If a domain object has other domain objects as fields, those fields will not be handled by the above method.
For that there are two choices. Firstly you can look at the field’s class type and say if t implements or extends your base Domain class/interface, you can deproxy them recursively.
In my case all domain objects implement a bare minimum interface called IEntity with only one getId() method.

the above method can be modified to recursively deproxy/sanitize a domain’s fields if they are proxied objects.


//.............
            Object val = getter.invoke(proxy, null);

                if (IEntity.class.isAssignableFrom(f.getType()) {
                    val=deproxy(val);//recursively deproxy the fields if they are enhanced objects
                }
                setter.invoke(entity, new Object[]{val});

If you only have to serialize a handful of domain objects, it might be better to register converters
for those fields at startup instead of using the above method.

Say, we have a domain class State with Country as one of its field, we can register the above converter to convert the country object as below.


//.............
//entity manager that handles all persistence needs
IEntityManager em= (IEntityManager) BeanFactory.getBean("entityManager");

//fetch a list of State objects with id smaller than3
       List<State> list= em.fetch(State.class, "id<3");

//uses factory method to instantiate Xstream
xstream xstream= XStreamFactory.getXstream(Format.JSON);

CGLIBEnhancedEntityConverter cglibConverter= new CGLIBEnhancedEntityConverter();

//register default converter
xstream.registerConverter(cglibConverter);

//register field converter. country field for State objects
xstream.registerLocalConverter(State.class, "country", cglibConverter);

//spit out the serialized json objects
 System.out.println(xs.toXML(list));

here’s the result without deproxying the domain object:
The before version :-)


{"list": [
  {
    "code": "",
    "name": "",
    "daylightSavingStart": "",
    "daylightSavingEnd": "",
    "CGLIB$BOUND": true,
    "CGLIB$CALLBACK_0": {
      "@class": "com.barahisolutions.proxy.EntityProxyFactory$EntityMethodInterceptor",
      "data": [
        {},
        {
          "default": {
            "loadFactor": 0.75,
            "threshold": 12
          },
          "int": 16,
          "int": 8,
          "string": "id",
//..................................................
//there's 10 times more of this garbage which i didn;t bother to print out.

And here's the nice and clean pojo version of the deproxied proxy objects.
I used the recursive option to inspect properties if objects and deproxy them if they are proxied domain
objects.
The after version :-)


{"list": [
  {
    "id": 1,
    "code": "NSW",
    "name": "New South Wales",
    "utcOffset": 10.0,
    "daylightSavingOn": false,
    "daylightSavingStart": "",
    "daylightSavingEnd": "",
    "country": {
      "id": 18,
      "code": "",
      "name": "Barbados"
    }
  },
  {
    "id": 2,
    "code": "VIC",
    "name": "Victoria",
    "daylightSavingOn": false,
    "daylightSavingStart": "",
    "daylightSavingEnd": "",
    "country": {
      "id": 12,
      "code": "AUS",
      "name": "Australia"
    }
  }
]}

I recently had to build a HTML select list with items grouped by category .
The list had to be populated using ajax as using simple jsp tag wasn’t enough as I needed other
properties besides simple key/ value and group for validation and displaying description of the selected item using javascript .

Since grouping objects can be quite quite handy for displaying grouped data in forms and in reports I ended up creating a utility method in java which takes a List of objects and a field name to group the objects by ,
and returns a map with keys as the values of the field name and values a a list of objects under this group.

Here’s the method .


    /**
     * Groups objects using field name provided
     *  @param list the list of objects to group
     * @param field the field to group the objects by
     * @return new Map containing list of objects.
     * The Map's key is the property specified in criteria object
     */

public static <V> Map<String,List<V>> group(List<V> list, String field) {

            //used for indexing to avoid too much looping
	     HashMap<String,K> index= new HashMap<String,K>();
      // the container for grouped data. K is the data type for the field's value.
        HashMap<K,List<V>> groupedData= new HashMap<K, List<V>>();

      // the method to invoke to get the value of the 'field' prop from objects
         Method m=null;

        try {
          V obj=list.get(0);
       // Used a handy Util Class's method for getting the getter method for 'field'
          m = ClassUtil.getMethod(obj.getClass(), "get"+StringUtil.getFirstUpper(field));
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(ListUtil.class.getName()).log(Level.SEVERE, null, ex);

            return null;
        }

       //iterate through the list of objects passed as parameter
        for (V object : list) {

	//the 'field' value of object
             K columnVal=null;

             try {
                    columnVal = (K) m.invoke(object, null);

                     // group of objects under columnVal group
                       List<V> group=groupedData.get(index.get(columnVal.toString()));

                if(group==null){
                    group= new ArrayList<V>();
                groupedData.put(columnVal, group);
                index.put(columnVal.toString(), columnVal);
                }
                //add the object to the group
                group.add(object);

                } catch (Exception ex) {
                    Logger.getLogger(ListUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
        }

        return groupedData;

}

here’s a simple test:


   List<Command> commands= new ArrayList();

//create objects to populate a list;

        Command comm= new DeviceCommand();
        comm.setCommand("CONTROL comm1");
        comm.setCommandType(CommandType.CONTROL);
        comm.setName(" CONTROL command 1");
        commands.add(comm);

          Command comm2= new DeviceCommand();
        comm2.setCommand("comm2");
        comm2.setCommandType(CommandType.CONTROL);
        comm2.setName(" CONTROL command 2");
        commands.add(comm2);

          Command comm3= new DeviceCommand();
        comm3.setCommand("INFORMATION comm1");
        comm3.setCommandType(CommandType.INFORMATION);
        comm3.setName("INFORMATION command 1");
        commands.add(comm3);

          Command comm5= new DeviceCommand();
        comm5.setCommand("SETTING comm1");
        comm5.setCommandType(CommandType.SETTING);
        comm5.setName("SETTING command 1");
        commands.add(comm5);

          Command comm6= new DeviceCommand();
        comm6.setCommand("SETTING comm2");
        comm6.setCommandType(CommandType.SETTING);
        comm6.setName("SETTING command 2");
        commands.add(comm6);

           Command comm8= new DeviceCommand();
        comm8.setCommand("OTHER comm1");
        comm8.setCommandType(CommandType.OTHER);
        comm8.setName("OTHER command 1");
        commands.add(comm8);

          Command comm4= new DeviceCommand();
        comm4.setCommand("CONTROL comm4");
        comm4.setCommandType(CommandType.CONTROL);
        comm4.setName("CONTROL  command 4");
        commands.add(comm4);

           Command comm7= new DeviceCommand();
        comm7.setCommand("SETTING comm3");
        comm7.setCommandType(CommandType.SETTING);
        comm7.setName("SETTING command 3");
        commands.add(comm7);

          Command comm9= new DeviceCommand();
        comm9.setCommand("OTHER comm2");
        comm9.setCommandType(CommandType.OTHER);
        comm9.setName("OTHER command 2");
        commands.add(comm9);

          Command comm10= new DeviceCommand();
        comm10.setCommand("OTHER comm3");
        comm10.setCommandType(CommandType.OTHER);
        comm10.setName("OTHER command 3");
        commands.add(comm10);

      //convert  list of Command objects into a map with commandTpe as key and list of Commands within
    // that group as  map value.
        Map<String,List<Command>> grouped=ListUtil.group(commands, "commandType");

	//print out the grouped map data.
        System.out.println(grouped.toString());

And the string representation of the grouped data :

{OTHER=[OTHER command 1, OTHER command 2, OTHER command 3], SETTING=[SETTING command 1, SETTING command 2, SETTING command 3], CONTROL=[ CONTROL command 1,  CONTROL command 2, CONTROL  command 4], INFORMATION=[INFORMATION command 1]}

why css still sucks for layout

June 11th, 2009 | Posted by admin in css | front end - (0 Comments)

I’m really pissed off with the CSS fanboys let me tell you. Their devotion to CSS-P is so religious that their collective argument sounds annoyingly rhetorical at best.
Is there such thing as pragmatism?? I’m aware that pragmatism isn’t always the desired way to build software and systems. Heck, If I’m building a software to control nuclear reactors, I would be scared to let my pragmatism rule the software design, I can’t risk blowing a whole city or country and I’d have to take utmost care in every step I take to ensure I follow proper protocols and procedures so I don’t fry a city or entire country accidentally.

But lets face it, designing a website is not the same as designing a nuclear reactor control system.
And as such I can afford to say screw semantics, screw standards, screw them all if they screw up my time and resources and force me to think less of design and shitload more of hacks to just get things right.
I don’t care to get things just right. I want things to be damn right to start with. And if semantically incorrect methods permit me to do so, so be it.

I was just wondering, if HTML table was repackaged with absolutely no changes to any of its markup structure and behavior and called grid and renamed tr,td,th too, would all the CSS-P fanboys use it??

    <grid>
    <row>
   < unit> "Grid Glory"
   < /unit>
   < /row">
   < /grid>

To me its utter nonsense to not use a feature just because of semantic concerns and feeble arguments of SEO, accessibility etc.

The thing that really pisses me off though is the fact that as soon as someone raises concern about CSS/DIV based designs, all the CSS fanboys gang up and point their fingers and tell people that the reason they have problem with CSS/DIV based layout is because they are just plain ass dumb.

These bright new fanboys are pretty fanatic and everywhere I read, their arguments are just the same. Standard arguments, boxed arguments.

And they talk about the amount of code in the markup that makes table-based layout horrible to maintain not to mention the bandwidth penalty.

As if the amount of css hack that has to be conjured to do simple layouts doesn’t need maintenance and as if it loads by magic on the browser and bandwidth issue becomes non-issue….

CSS /DIV based layout is counter-intuitive to say the least. Who starts thinking in terms of float and clear when designing anyway??
If I want to add a new element to the a layout, I not only have to think about the size of the element but I have to make damn sure that the rest of the page doesn’t break by a mere addition of an element in a page. Which forces me to look at the whole design in terms of pixels, margins and paddings to add be able to add
a new element to a layout item. And that doesn’t prevent content/elements bleeding off the layout container.

And how about overlap problems??
I can break the best laid out CSS site by merely adding one more element to it……

CSS has merely opened a new job market and allowed people to make loads of money out of it. And the fanboys of CSS/DIV layout guard their self-interest with great zealot because without CSS they will be out of jobs. I mean, who’s going to write a page full of CSS hack to give us merely a 3-column fluid layout with column-size constraints. And then they write one more page full of CSS hacks to prevent the content from bleeding out of their containers, with partial success.

Web-development has taken a great leap backward as a result of the push to use CSS/DIV/SPAN for layouts.
Because we spend most of the time not in designing pages but in applying hacks to make them look devent on most browsers.

If the fanboys close their eyes for one minute and forget everything bad that had been hammered into their head about tables and think of it as a grid, u’ll be damn surprised how intuitive it is to design in terms of grids. All decent desktop GUI toolkit provide grid-based layout which allows us to apply constraint to layout grid-elements in relation to other grid elements and so on.

Why?

The fanboys might argue that the GUI toolkit designers were mere dumb people who still hold on to the grid-based layout of last century and blah blab and some more blah.

And when the fanboys run out of ammunition, they fallback to blaming browsers and declare its the fault of browsers and nothing else.
And meanwhile they bleed to death trying to make a simple layout work in most browsers with tons of css hacks which still doesn’t quite do the job. why?

CSS is ill-equipped to handle layouts…..The language or pseudo-language of CSS was designed by people who have no knack for Designs, if they did, the language would have been more intuitive than this terrible piece of work. I come from a programming background and I love beautiful designs and I like to pretend I can create cool designs and sites. For me CSS/DIV layout makes no sense from either a programmer’s prespective or a designer’s.

From a programmer’s perspective I like parameter driven development to simplify things, and from a designers perspective, I’d hate to have to hand-code the whole friggin page design and have to come up with countless hacks to overcome both CSS and browser shortcomings.

CSS sucks so bad that even though billions of people use the internet everyday, yet no decent visual designing tool has come out so far. The one decent WYSWYG editor Dreamweaver fails miserably when designing layouts in CSS.
Where’s the forward mobility promised by this new technology??