dinsdag 25 maart 2014

Test with Wicket and Spring

Introduction:

I started working with Wicket and as a Java developer I like the concept. I think when there are really front end developers working, it is harder to defend the fact that you want to use wicket. Wicket brings it own html notations. Most frontenders are not keen on that. For working with Wicket there is a very good starting point: the wicket free guide. The interesting part starts when you are about to use DI and Wicket. Setting that up is not to hard The web.xml should look like this:

<web-app>
  <display-name>MyApp</display-name>
  <filter>
  <filter-name>MyAppFilter</filter-name>
  <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
  <init-param>
  <param-name>applicationClassName</param-name>
<param-value>com.my.app.MyApp</param-value>
  </init-param>
  </filter>
  <filter-mapping>
    <filter-name>MyAppFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

For maven just get the latest version of wicket and spring and you be up and running in no time.

The problem:

The thing i ran into was the part where I wanted to start testing with Wicket using some DI to deal with some Classes which otherwise would end up in a very complex design. So the thing I cooked up after reading a lot of examples on the internet that didn't work.

The spring test config in src/test/resources:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  <bean id="classa" class="com.myapp.ClassA">
</bean>
  <bean id="classb" class="com.myapp.ClassB">
</bean>
 <bean id="wicketApplication" class="com.myapp.MyWicketApp">
</bean>
</beans>

The Junit test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:myApp-test-context.xml" })
public class LoginTest {
private WicketTester wicketTester;

@Inject
        // this stub is inheriting from an abstract class which is enhiriting from the wicket
          WebApplication otherwise I cannot DI with the same type. The real app is also inheriting from
           that abstract class
private AmyApp myAppStub;

@Before
public void init() {
wicketTester = new WicketTester(myAppStub);
}
}

The mock Application:

public class MyAppStub extends AmyApp {
private final ApplicationContextMock applicationContextMock = new ApplicationContextMock();
       //injecting the classes from the test context.
@Inject
private ClassA classa;
@Inject
private ClassB classb;

protected ApplicationContextMock getApplicationContextMock() {
return applicationContextMock;
}

@Override
public Class<? extends Page> getHomePage() {
// TODO Auto-generated method stub
return null;
}

@Override
public void init() {
                //Adding the injected classes to the context mock so they will be used during testing.
applicationContextMock.putBean("classa",
classa);
applicationContextMock.putBean("classb",
classb);
                //adding the applicationmock to spring
getComponentInstantiationListeners().add(
new SpringComponentInjector(this, applicationContextMock));
}

}

Conclusion:

After I figured out how this baby works it is not that hard anymore to test with wicket. All you have to do is figure out the right pieces of the puzzle. In all the other examples the same pieces where missing.

I hope This helps.

Have Fun!

dinsdag 18 maart 2014

CDI (context dependency injection JSR 299) and Junit Testing.

Introduction:

DI is unthinkable these days. Having different variations on the same concept in different classes and of course a   separate context for testing. Although for testing mocking instead of stubbing is also a  very valid option. I have been playing around with Spring and with Google guice but I never came around to play with CDI. I have been playing with it today And I must say it is quiet charming. I really loved the simple and direct way of annotating stuff and no traces of xml files (only if you want too).

The part I want to describe is the part to use for testing. It reminds me a lot of how that works with spring apart from the fact that I did not had to point to a context.xml file.

The example:

Because the jsr 299 is a reference, the main parties allready have build there implementation for it :

(The versions are at this point in time (march 2014) the latest.

  • JBoss it would be: 

<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.2.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
  • Apache
<dependency>
<groupId>org.apache.openwebbeans</groupId>
<artifactId>openwebbeans-impl</artifactId>
<version>1.2.2</version>
</dependency>

To write a piece of code that chooses the depedency for its needs CDI is great in being simple:

The interface that makes the difference:

public interface IHelloWorld {

void sayHello();

}

The class that does my realtime serious business kind of logic:
import javax.enterprise.inject.Alternative;
//This annotation tells the CDI container that it is one of the many implementations.
@Alternative
public class HelloWorld implements IHelloWorld {

public void sayHello() {
System.out.println("Hello world");
}
}

The class that does my very serious alternative kind of business logic or test stubbing.
import javax.enterprise.inject.Alternative;
//This annotation tells the CDI container that it is one of the many implementations.
@Alternative
public class HelloAlternative implements IHelloWorld {

public void sayHello() {
System.out.println("hello alternative world");
}


The class that is complete unaware of the fact that he does not speak to the same injected all the time. Love to keep this one in the dark about that.

import javax.inject.Inject;

public class LoginBean {

        //This is the actual injection of the desired class.
@Inject
private IHelloWorld helloWorld;

public void print() {
helloWorld.sayHello();
}
}

The first test that uses my very serious business logic saying: "Hello world "

import javax.inject.Inject;

import org.jglue.cdiunit.ActivatedAlternatives;
import org.jglue.cdiunit.CdiRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

//The annotation that hooks this test up with te CDI container
@RunWith(CdiRunner.class)
// The annotation that tells which implementation of the IHelloWorld Interf to use.
@ActivatedAlternatives(HelloWorld.class)
public class HelloWorldTest {
         //Injects the bean that has a DI itself.
@Inject
LoginBean loginBean;

@Test
public void test() {
loginBean.print();
//outcome : "Hello world"        


}

import javax.inject.Inject;

import org.jglue.cdiunit.ActivatedAlternatives;
import org.jglue.cdiunit.CdiRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

//The annotation that hooks this test up with te CDI container
@RunWith(CdiRunner.class)
// The annotation that tells which implementation of the IHelloWorld Interf to use.
@ActivatedAlternatives(HelloWorld.class)
public class HelloAlternativeTest {

@Inject
LoginBean loginBean;

@Test
public void test() {
loginBean.print();
//outcome: hello alternative world
}

At last but not least the full Apache maven tech stack:


<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.jglue.cdi-unit</groupId>
<artifactId>cdi-unit</artifactId>
<version>2.1.0</version>
<scope></scope>
</dependency>

And the full JBoss maven tech stack:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0</version>
</dependency>

<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.jglue.cdi-unit</groupId>
<artifactId>cdi-unit</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.2.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>

Conclusion:

If you are using the Apache stack and you want to move to the JBoss stack or visa versa, that does not mather. They bot comply to the JSR 299. There is no need for code changing. To me personal this way of DI is more intuitive and very powerfull by the annotatons it is using. Give it a try and let me know what you think of it.

Have fun! 


dinsdag 11 maart 2014

Find position and insert characters




Introduction:

I was working on formatting wrongly entered numberplates of a car. One business rule was to format all of them in the right perspective. Like 11aa33 should be 11-AA-33. But how to find out where to put the minusses.

The solution

 First of all make sure you only have capitals like:

numberplate.toUpperCase();

This takes care of all the characters in the numberplate.

The second step is:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

    private static final String MINUS = "-";
    private static final String DIGIT_MATCH = "[0-9]{1,3}";
    private static final String CHARACTER_MATCH = "[A-Z]{1,3}";

        String formatted = kenteken;
//counting the right amount of minusses.
if (StringUtils.countMatches(kenteken, MINUS) != 2) {
           //the actual patterns to find
            Pattern digitPattern = Pattern.compile(DIGIT_MATCH);
            Pattern charsPattern = Pattern.compile(CHARACTER_MATCH);
          // find the matches
            Matcher digitMatcher = digitPattern.matcher(formatted);
            Matcher charsMatcher = charsPattern.matcher(formatted);
            
             // adding the minusses
            if (digitMatcher.find()) {
                formatted = new StringBuffer(formatted).insert(
                        digitMatcher.end(), MINUS).toString();
            }
            if (charsMatcher.find()) {
                formatted = new StringBuffer(formatted).insert(
                        charsMatcher.end(), MINUS).toString();
            }
        }

        return formatted;

Have fun!

zondag 9 maart 2014

the power of javaassist

Introduction:

Just for fun I tried to weave a method into a class. I have been googling around to find the answers I needed to work wit javaassist. There where a lot of examples that drilled down to the same point and where not working. So i tried a bit and combined some of the stuff together.

The setting:

package org.injector.binding;

import org.injector.annotations.ComponentScan;

This pore litle guy has to say a lot but has no acces to the outside world.

public class CreateSetterStub {
private String greetingsGrashopper;

}

Luckely he has a good friend we are going to meet soon. Here we are going to call him:

public void test() {
                 // The one that needs help
Class class1 = CreateSetterStub.class;
               // Reaching out the helper.
CreateMemberSetter createMemberSetter = new CreateMemberSetter();
createMemberSetter.createSetter("greetingsGrashopper", class1.getName());
try {
CreateSetterStub createSetterStub = (CreateSetterStub)class1.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

       // The friend that is going to help
Class createSetter(String memberName,  String className) {

//The standard classpool as ued by javaassist
                ClassPool pool = ClassPool.getDefault();
// The stanndard classtype as used by javaassist
                CtClass cc = null;
//Here we teached the poor litle creature to speak.
                Class clazz = null;
try {
       Typing the speachless into the javaassist type.
               cc = pool.get(className);
         //pruning itself is a good thing: To reduce memory consumption, pruning discards                                           unnecessary attributes. But if you dont stop, you get errormessages about it. Your flow
             stops.
             cc.stopPruning(true);
             //Creating a method to speak to the outside world.
            CtMethod m2 = CtNewMethod.make("public String getText(){return \"hello world\"" + ";"
               + "}" , cc);
              //adding the method to the class. 
            cc.addMethod(m2);
           create a copy of the original class otherwise you get errors about the same class on the
              claspath.
              cc.replaceClassName(className, className + 2);
              //Type it back to the normal Java Pojo kind a type.
           clazz = cc.toClass();
              // print out the desired message. 
System.out.println( clazz.getDeclaredMethod("getText", null).invoke(clazz.newInstance(),null));
              //Still a load of exception handling todo :).
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return clazz;

Conclusion:

Dealing with javaassist is actually amazingly simple. It has a lot of power. In that perspective, it is wise to use it when needed not for convinience. As allways with power comes responsibility :).

Have fun.