EasyMock IArgumentMatcher

When EasyMock is used to set expectations we might need to specify what parameters are used to call a method on the mock object. An ‘IArgumentMatcher’ is used for this purpose as this section from the EasyMock documentation describes.

Sometimes it is desirable to define own argument matchers. Let’s say that an argument matcher is needed that matches an exception if the given exception has the same type and an equal message. It should be used this way:

 
     IllegalStateException e = new IllegalStateException("Operation not allowed.")
     expect(mock.logThrowable(eqException(e))).andReturn(true);

I wanted to specifically check if the argument matcher matches a parameterized java.util.Set with a certain number of elements in it. This is how I am able to do it.

So here I pass the expected size of the Set as a constructur parameter but I use Generics reflection to get the raw type for comparison. The idea to use an anonymous class in the line

 

   SetReturnTest<ObjectInstance> returnTest = new SetReturnTest<ObjectInstance>( set.size() ){};

to preserve the raw type at run-time is from Neil Gafter.

It does seem that not all raw types are erased in all cases. This is still hard to do and I believe I get Generics wrong in many cases.


package com.monitor.test.suite.mock;

import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;

import javax.management.ObjectInstance;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;



public class SetReturnTest<T> implements IArgumentMatcher {


    /**
     * The expected reflective type of objects in the returned java.util.Set
     */
    Type objectTypeExpected;
    /**
     * The expected size of the returned java.util.Set
     */
    protected int size;
    /**
     * The reflective type of objects in the returned java.util.Set
     */
    protected Type type;

    /**
     * The type and number of the objects in the java.util.Set
     * .
     */
    public SetReturnTest( int size ) {
        /**How many are expected in the java.util.Set?*/
        this.size = size;
        /**
         * The  parameterized type is matched
         * with the actual type expected at run-time.
         *
         */
        ParameterizedType pt =
                    (ParameterizedType) (getClass().getGenericSuperclass());
        type = pt.getActualTypeArguments()[ 0 ];
    }

    /**
     * EasyMock via the static method reportMatcher(IArgumentMatcher matcher), 
     * and return a value so that it may be used inside the call (typically 0, null or false). 
     */
    public Set eqSet( Type type, Set set ) {
        objectTypeExpected = type;
        SetReturnTest<ObjectInstance> returnTest = new SetReturnTest<ObjectInstance>( set.size() ){};
        EasyMock.reportMatcher( returnTest );
        return null;
    }


    /**
     * The actual java.util.Set is compared with the
     * one expected by the mock test. There are unchecked
     * warnings here but this seems to be the best possible attempt.
     */
    public boolean matches( Object actual ) {

        /** Unchecked is a potential problem*/
        @SuppressWarnings("unchecked")
        SetReturnTest setReturnTest = (SetReturnTest) actual;

        if( setReturnTest.size != size ){
            return false;
        }
        Type clazz1 = setReturnTest.type;
        Class clazz2 = (Class)objectTypeExpected;

        boolean match =
                clazz2.isAssignableFrom( (Class)clazz1 );

        return match;
    }

    /**
     * Append a simple error to identify which
     * matcher was used.
     */
    public void appendTo(StringBuffer buffer) {
        buffer.append( "SetReturnTest matcher" );
    }
}

Mock tests for JMX

There is not much scope for this blog if code is posted without explanation but I can explain only what I understand. There is magic going on behind this code.

I had to write mocks for some JMX classes for a project that I could not convince the management to use. JMX is a useful toolkit to monitor complex pipelines of processes and is integral to DevOps. So firms that want to leverage this idea should think differently.

Does it seem logical ?

This argument fell flat on its face.

This code mocks “ManagementFactory.getPlatformMBeanServer()” and in doing so I exercised EasyMock. It is not easy to mock statics but these EasyMock annotations help. So I am able to set the expectations and make the Platform Bean Server return a mock of the MBeanServer. This is very useful because now I can register MBeans and write more mock tests.

@RunWith(PowerMockRunner.class)
@PrepareForTest(ManagementFactory.class)
@PowerMockIgnore(value = {"javax.management.*"})
public class MBeanQueryTestCase  extends MonitorTestCase {


    private MBeanServer mBeanServerMock;

    private final String CLASSNAME = this.getClass().getName();

    @Before
    public void setUp() throws Exception {
        mockStatic(ManagementFactory.class);
        expect( ManagementFactory.getPlatformMBeanServer() ).
                                    andReturn( EasyMock.createMock(MBeanServer.class) );

        replayAll();
        mBeanServerMock = ManagementFactory.getPlatformMBeanServer();
        verifyAll();

    }
}

Mock testing is another useful toolkit in the arsenal of a hardy developer but that is another idea that fell flat on its face.

Habit of reading source code

Reading code can be very enlightening but I have been following this practice only recently.One might come across nuggets that explain a particular code pattern clearly when one reads code.
Twitter has open-sourced its ‘Commons’ library and I came across the Curiously Recurring Generic Pattern and the Self-bounding pattern in it. These two are discussed in ‘Thinking in Java’ by Bruce Eckel. He also gives an exercise at the end of Page 709.

Exercise 34: Create a self-bounded generic type that contains an
abstract method that takes an argument of the generic type parameter and
produces a return value of the generic type parameter. In a non-abstract
method of the class, call the abstract method and return its result. Inherit
from the self-bounded type and test the resulting class

The code for this exercise could be

public abstract class SelfBound< T extends SelfBound<T>>{

    public abstract T get( T t );

    public T getValue( T t){
         return get( t );
    }

public class SubSelfBound extends SelfBound{

    
    public SubSelfBound get(SubSelfBound subSelfBound) {
        return this;
    }

    public static void  main( String[] argv ){

        SubSelfBound subSelfBound = new  SubSelfBound();

        subSelfBound.test();
    }

    private void test() {

        SubSelfBound subSelfBound = new  SubSelfBound();

        subSelfBound =  getValue( subSelfBound );//The sub-class's inherited method is forced
                                                 //to take only the derived type as parameter
                                                 //and not the base type. The parameter varies
                                                 //and matches the derived type( Covariant )
        
        SelfBound selfBound =  getValue( subSelfBound );//It also returns the super type.
                                                        //This is related to the covariant
                                                        //return types according to the book.

    }
}

Even though I might not have the absolutely correct solution here the idea is clear and it is that the Curiously Recurring Generic Pattern and the Self-bounding pattern are similar and the Self-bounding pattern permits a type of covariant argument types.

I used to think only covariant return types are possible in J2SE 5 but there seems to be a way to implement covariant argument types also though the practical applications of this concept could stupify the developers because not many are
used to advanced generics.

I understood all of this by reading the Twitter Commons source code that has used self-bounding types like this.

public interface Unit<U extends Unit<U>>;{

  double multiplier();
}


If one is not used to thinking about Java generics deeply this type of code will be
hard to understand and implement.

JoinPoint Matching Covariant methods

AspectJ JoinPoint matches methods with Covariant return types. The ‘declare warning’ construct seems to be a useful way of testing because the eclipse markers show the match.

Eclipse View

Aspect

declare warning: execution(Collection<? extends Test> *.test( .. )) : "Covariant";


package com.test;

import java.util.Collection;

public class CovariantSub extends CovariantSuper{

	public Collection<Test> test(){
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public Class test1(){
		return null;
	}

}

package com.test;

import java.util.Collection;

public class CovariantSuper {

	public Collection<? extends Test> test(){
		return null;
	}

	public Class<?> test1(){
		return null;
	}

}

Commodity software or expensive tool

We use a scheduler/file transfer tool from a smaller vendor to avoid costs and huge upfront investments. This financial project has very strict SLA’s. Would a more expensive solution help ?

There are many open-source tools that can do the same thing. We used WebSphere portal that works but I have also seen a open-source stack built using open-source WSRP etc. that can be used to build portals.

Actually there is one more fundamental problem. That is the company’s technology culture. If the culture is not conducive to technical software development or testing then good quality or scalability cannot be ensured.

Basically I think that delivering good SLA’s means clusters, performance testing, HA etc.

Not an expensive tool. Even a very expensive tool needs strong testing teams and a test environment that matches the production environment. So when the management does not understand fundamental testing principles we are going to be in trouble.

Recently we faced one of the many problems that are stopping us from delivering our software. The scheduler that we use is from Flux. Due to a browser upgrade issue the web console of this tool would not open in our production servers. Monitoring became harder.

Red tape ensured that this situation could not be overcome easily. Usually tools have facilities to manipulate the runtime through backend code.

WebSphere Portal has XMLAccess. The Flux engines forming a cluster can be accessed using
the following Java code. This code was able to recover a failed Flow chart and saved the day.

I feel that if the people who we are working with are not good, the best and the most expensive tools in the world cannot help us deliver good software.

So in the end it was working code that fixed the problem.

package com.test;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import flux.Cluster;
import flux.Engine;
import flux.EngineException;
import flux.EngineInfo;
import flux.Factory;
import flux.FlowChart;
import flux.FlowChartIterator;

public class LookupEngine {

	public static void main( String... argv ) throws IllegalArgumentException, RemoteException, NotBoundException, EngineException{
		assert( null != argv[ 0 ] );
		assert( null != argv[ 1 ] );
		assert( null != argv[ 2 ] );
	    Factory factory = Factory.makeInstance();
	    LookupEngine le = new LookupEngine();
	    le.
	    lookupCluster( factory,
	    		       argv[ 0 ],
	    		       argv[ 1 ],
	    		       argv[ 2 ]);
	}
	
	private void lookupCluster( Factory factory,
			                    String host,
			                    String namespace,
			                    String bindName ) throws IllegalArgumentException,
			                       		       NotBoundException,
                                                               EngineException,
                                                               RemoteException{
		Cluster cluster =
		    factory.lookupCluster( host,
		                           1099,
		                           bindName,
		                           "user",
		                           "password" );
        Engine engines = null;
	for( Object engine : cluster.getEngines() ){
		System.out.println( engine );
                engines = ((EngineInfo)engine).createEngineReference();
	}
        FlowChartIterator iterator = null;
	for( iterator = engines.get() ; iterator.hasNext() ; ){
                          //Get FlowChart name
		System.out.println( (( FlowChart )iterator.next() ).getName());
        }
        
        
        iterator.close();
        //So once we find the name of the FlowChart we can recover it.
        //engines.recover( "/NameSpace/FlowChart" );
                
                 
	}
	
}

Enum value matching using AspectJ

I wrote an Aspect to advise a particular constant-specific method.

What is a constant-specific method ?

The J2SE 5 documentation explains it.

“You can declare the method abstract in the enum type and override it with a concrete method in each constant. Such methods are known as constant-specific methods.”

There is an example here.

The enum is

package com.test.generics;

import java.util.Collection;
import java.util.List;
import java.util.Set;

public enum TestEnum {
    Value1{
        public &lt;T> List<T> getValue(){ return null; }
        public <T> List<T> getSameValue(){ return null; }
   },
   Value2{
        public <T> Set <T>getValue(){ return null; }
        public <T> List<T> getSameValue(){ return null; }
   };

   abstract <T> Collection<T> getValue();

   abstract <T> Collection<T> getSameValue();

	public static void main(String[] args) {
		System.out.println( Value1.getSameValue() );
		System.out.println( Value2.getSameValue() );
	}

}
package com.test;

import java.util.List;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import com.test.generics.TestEnum;

@Aspect()
public class EnumAspect {

              /*
                  Matches a particular method of all enum values
               */             
	@Pointcut(
	"execution(List<T> getValue())" )
	public void testPointcut(){};

	@Before("testPointcut()")
	public void test() {
		System.out.println( "Generics aspect" );
	}

                /*
                  Matches a method of a particular enum values
               */   

	@Pointcut(
	"execution(List<T> getSameValue()) && target(testEnum) && if()")
	public static boolean testPointcut1( TestEnum testEnum ){
		return testEnum == TestEnum.Value2;
	}

	@Before("testPointcut1(testEnum)")
	public void test1( TestEnum testEnum ) {
		System.out.println( "Generics aspect [" + testEnum.ordinal() + "]" );
	}

}

The if() pointcut expression with an empty body is used and the testPointcut1 method tests for the value of the enum. There does not seem to be a JoinPoint matching pattern to pick out certain enum values automatically. It looks like a pattern would be useful.

Update : Raised an enhancement request.

Update : 26 Oct 2020

One of the contributors who has commented here pointed out that this aspect works. I am not sure if this would have worked 12 years back when I raised the request. At that time I thought it was a missing feature.


@Aspect
public class EnumAspect {
@Pointcut("execution(java.util.Collection+ getValue()) && target(testEnum) && if()")
public static boolean testPointcut1(TestEnum testEnum) {
return testEnum == TestEnum.Value1;
}

@Before("testPointcut1(testEnum)")
public void test1(JoinPoint joinPoint, TestEnum testEnum) {
System.out.println(joinPoint + " -> " + testEnum);
}

@Pointcut("execution(java.util.Collection+ getValue()) && target(testEnum) && if()")
public static boolean testPointcut2(TestEnum testEnum) {
return testEnum == TestEnum.Value2;
}

@Before("testPointcut2(testEnum)")
public void test2(JoinPoint joinPoint, TestEnum testEnum) {
System.out.println(joinPoint + " -> " + testEnum);
}

}

RIA Benchmarking

I found this RIA benchmarking very cool. I was looking for a paging AJAX pattern. Is the last option, ‘Flex paged’ a paging pattern ? Have to investigate.

JSF JSR 168 Portlet problem

We have been struggling to understand how the JSF Portlet bridges work in different versions of the IBM RAD. We are using RAD 7 and the bridge is different from the one we were using with RAD 6.

One saving grace is that the design of the JSF API is quite flexible. ViewHandlers are chained. So I could implement my own ViewHandler and it did not cause any problems for the ViewHandler that the bridge API implements.

I came across this JSR 301 and it looks like this is needed to ensure that the next version of the Portlet spec. works properly with JSF implementations.

Where is the deployed EAR ?

Offshore software development is very stressful. There is usually a client manager who wants something and a software lead who thinks that the manager is foolish. Recently I heard this conversation between the lead and the manager.

Manager : I want you to deploy the new EAR.

Lead : I don’t have any problem with that but you should know that it is not tested.

Manager : So you have the backup of the previous EAR ? If anything goes wrong we can deploy the backed-up EAR.

Lead : No. We don’t have that.

Manager : This is ridiculous. You are saying that the EAR is deployed but you don’t have it.

Lead : I’ve explained this many times. There is no EAR in the deployed location.

Manager : I don’t understand. Where is the previous EAR ?

At this point the software lead loses his temper.

hmmmm. There is no EAR in the deployed location in WebSphere ??

What is this command supposed to do ? It is the backup or atleast the previous EAR.

$AdminApp export FacesPortletTracker_PA_m3pfnqy C:/test/FacesPortletTracker.ear

Java 5.0 Enums – constant-specific methods

I recently used Java 5.0 Enums to represent directions in a compact way. These methods in the Enum are called constant-specific methods. Apart from type-safety they also provide constant-specific behaviour.


/*
* Enum representing the current direction and its left and right
* directions.
*/


public enum EnumDirection {


SOUTH( 1, "SOUTH" ){
public EnumDirection turnLeft() {
return EAST;
}


public EnumDirection turnRight() {
return WEST;
}
},


EAST( 2, "EAST" ){
public EnumDirection turnLeft() {
return NORTH;
}


public EnumDirection turnRight() {
return SOUTH;
}
},


NORTH( 0, "NORTH" ) {
public EnumDirection turnLeft() {
return WEST;


}
public EnumDirection turnRight() {
return EAST;
}
},
WEST( 3, "WEST" ){


public EnumDirection turnLeft() {
return SOUTH;
}
public EnumDirection turnRight() {
return NORTH;
}

};


public abstract EnumDirection turnLeft();


public abstract EnumDirection turnRight();


private String direction;


private int number;


EnumDirection( int number, String direction ) {
this.direction = direction;
this.number = number;
}


public String getDirection(){
return direction;
}


public String getDescription( ) {
switch( this ) {
case NORTH: return "NORTH";
case SOUTH: return "SOUTH";
case EAST: return "EAST";
case WEST: return "WEST";
default: return "Unknown Direction";
}

}


public static EnumDirection getDirection( int number ) {
switch( number ) {
case 0:
return EnumDirection.NORTH;
case 1:
return EnumDirection.SOUTH;
case 2:
return EnumDirection.EAST;
case 3:
return EnumDirection.WEST;
default:
return EnumDirection.EAST;
}

}


public void printString() {
System.out.printf("%s %d%n", NORTH, NORTH.direction);
System.out.printf("%s %d%n", SOUTH, SOUTH.direction);
System.out.printf("%s %d%n", EAST, EAST.direction);
System.out.printf("%s %d%n", WEST, WEST.direction);
}


public int getNumber() {
return number;
}


}