testalicious testing

3 11 2008

Test Mashup, TDD / BDD

So these days test driven or behavior driven development are hot around my coordinates. Im going to write a bit about pratical usage of BDD using selenium & jBehave. With backup tools such as maven, cobertura and selenium.

We all hate to maintain large code bases of tests, tests are nice ( and necessary ) but sometimes you just get cluttered by them.

Introducing jBehave

So what if you could have a minimal amount of code and write something like this:

When user goes to homepage
homepage are rendered

Taking it a bit further:


Given a user nino with password dummy
When user goes to homepage and does a login
Then user are logged in and shown profilepage

That would be nice right? In jBehave you archive this by a blend of things, i’ll only cover a subset.

Steps
In your steps class you something like the below code, notice that I put in selenium. So the steps are sort of a mini test framework which the scenarios can utilize.


@When("a user visits $page")
public void visits(String page) {
selenium.open("http://localhost:8080/" + page);
}
@Then("$page are rendered")
public void seesPage(String page) {
Ensure.ensureThat(selenium.getLocation().compareToIgnoreCase(
"http://localhost:8080/" + page) == 0);
Ensure.ensureThat(!selenium.isTextPresent("HTTP ERROR: 404"));
}

Scenario
The scenario are a plain text test, which utilizes the steps above. Something like this:

When a user visits homepage
Then home are rendered
When a user visits errorpage
Then errorpage are rendered

As you can see you could actually put in use cases, and things suddenly got a lot easier to discuss with customers, your tests are readable by non technical eyes and of course it’s not limited to web development. And your maintenance code base got smaller since what you need to write in java have shrunken, you are only building a small framework for the scenarios to utilize. Really really cool!

As you can see jBehave fit’s both for unit testing and the more obvious integration testing.

Introducing Cobertura

While you test it’s still nice to know your code coverage, cobertura’s nice for this as it gives you simple readable reports and it’s transparent to use. Just include a small mojo in your parent pom:

In your parent pom

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemProperties>
<property>
<name>
net.sourceforge.cobertura.datafile
</name>
<value>
target/cobertura/cobertura.ser
</value>
</property>
</systemProperties>
</configuration>
</plugin>

And in the project pom using it

<plugins>

<reporting>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<configuration>
<formats>
<format>html</format>
</formats>
</configuration>
</plugin>

</plugins>
</reporting>
</project>

You will then get reports looking like this:

Cobertura report

Cobertura report

And you can even see which lines are touched in your code:

See what lines are touched by tests

See what lines are touched by tests

Introducing Selenium

Automatic independent browser tests, if your doing web development this is almost a must have, unless you like to do manual tests a lot. However if you are using code coverage which are using byte code instrumentation, you could loose track of what’s tested and what not. A way around this are perhaps to start a embedded jetty server as part of your test, then in theory you should be back on track. Since byte code instrumentation should be able to track again…





JPQL example queries

28 10 2008

Looking for JPQL queries, look no further. I use this as a reference page myself.

Search for Persons which all live in San Fransisco, New York or Frederikssund, traversal over single relation

SELECT p FROM Person WHERE p.city.id IN ("SF","NY", "FS")

Search for Persons with some of these tags(tags is a list of tags), traversal over list relations: Married, Divorced, OverTheHill

SELECT p FROM Person P JOIN p.tags t WHERE t.name IN ("married","divorced", "overthehill")

Above could be slow..
Search with enumerations:

SELECT p FROM Person WHERE p.enum = com.mypackage.enum.value
</code

Copy paste stuff:

public List searchForEvents(City city,
List eventTypeList,
List eventAdmittance,
List categoryTypeList)
{
List events = new ArrayList();
List categories = new ArrayList();
List admittanceTypes = new ArrayList();
if (eventTypeList.size() > 0 || categoryTypeList.size() > 0
|| eventAdmittance.size() > 0) {
for (EventType event : eventTypeList) {
events.add(EventType.class.getCanonicalName() + "."
+ event.name());
}

for (CategoryType categoryType : categoryTypeList) {
categories.add(CategoryType.class.getCanonicalName() + "."
+ categoryType.name());

}
for (EventAdmittanceType admittanceType : eventAdmittance) {
admittanceTypes.add(EventAdmittanceType.class
.getCanonicalName()
+ "." + admittanceType.name());

}

}
String jpql = "select e from Event e WHERE e.city.id='" + city.getId()
+ "'";
// types
List typesList = new ArrayList();

if (events.size() > 0) {
typesList.add("e.eventType IN ( " + buildJPQL(events, ",") + " ) ");
}
if (categories.size() > 0) {
typesList.add(" e.categoryType IN ( " + buildJPQL(categories, ",")
+ " )");
}
if (admittanceTypes.size() > 0) {
typesList.add(" e.eventAdmittanceType IN ( "
+ buildJPQL(admittanceTypes, ",") + " )");
}
if (typesList.size() > 0) {
jpql += " and " + buildJPQL(typesList, "and");
}

return getJpaTemplate().find(jpql);
}

private String buildJPQL(List sqlList, String delimiter) {
String constructedSQL = "";

for (String subSQL : sqlList) {
constructedSQL += subSQL + " " + delimiter;
}

if(sqlList.size()!=0){
constructedSQL = constructedSQL.substring(0, constructedSQL.length()
- delimiter.length());

}

return constructedSQL;
}





Stack page

7 10 2008

This is my stack page. Opensource tools that I use, find interesting or need to remember will be listed there:

In use (partial list):
http://wicket.apache.org/
http://wicketstuff.org/
http://sourceforge.net/projects/wicketopia/
http://mojo.codehaus.org/cobertura-maven-plugin/
jpa http://java.sun.com/javaee/5/docs/api/javax/persistence/package-summary.html
http://www.hibernate.org/
http://www.springframework.org/
http://browsershots.org/ (when I need to test cross platform browser)
http://geo-google.sourceforge.net/

https://simple-log.dev.java.net/
http://jbehave.org/
JTS / Hibernate spatial

Maven plugin:

http://maven.apache.org/plugin-developers/cookbook/add-svn-revision-to-manifest.html

Images / Art / Icons for applications free via creative commons or similar
http://tango.freedesktop.org/
http://www.everaldo.com/crystal/
http://www.famfamfam.com/lab/icons/silk/
http://www.deviantart.com/
http://www.iconfinder.net/

Tools to help your css:

http://www.cssjuice.com/tools/
http://www.roundz.net/

Interesting:

http://dev.eclipse.org/blogs/kmitov/2009/06/12/jpicus-the-tool-for-java-io-analysis/
http://sixrevisions.com/resources/40-beautiful-free-icon-sets/

http://picocontainer.org/

http://www.jdave.org

http://geoserver.org/
http://code.google.com/p/google-guice/
http://links.sourceforge.net/
http://www.dillo.org/
http://sourceforge.net/projects/protogen/
http://sourceforge.net/projects/qwick/

http://code.google.com/p/liquidform/
J2ME stuff:
https://meapplicationdevelopers.dev.java.net/mobileajax.html

Trouble shooting:

https://visualvm.dev.java.net

Desktop development:

http://publicobject.com/glazedlistsdeveloper/
https://appframework.dev.java.net/

funstuf

http://slick.cokeandcode.com/

jmoneyengine

documentation:

http://repo.exist.com/dist/maestro/1.7.0/BetterBuildsWithMaven.pdf
http://apollo.ucalgary.ca/tlcprojectswiki/index.php/Public/Subversion
http://apollo.ucalgary.ca/tlcprojectswiki/index.php/Public/Project_Versioning__Best_Practices#Build_Versioning

http://books.google.dk/books?id=zGgZ850Aw5gC&pg=PA1&lpg=PA1&dq=Beginning+Ubuntu+Server+Administration&source=bl&ots=6I0rezDNZY&sig=pAR-0kD7PxnlBAY5w0cw98ndWU0&hl=da&ei=SMB6SsPwA4OL-QaDvNVW&sa=X&oi=book_result&ct=result&resnum=4#v=onepage&q=&f=false

Project Stitching Spider

CI : https://hudson.dev.java.net/ / http://continuum.apache.org

Issue : http://jtrac.info/

WIKI: http://www.xwiki.org

SVN:http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91 / http://www.visualsvn.com/server/





Apache Wicket javascript integration

9 09 2008

This article will give some general pointers on howto do javascript integration, it’ll give some tip on how to make it easier to for you. And also a recommended way on project structuring.

Howto do it:

Javascript bridge

If you need a javascript bridge between the javascript library and wicket a very nice way are todo it like this:
https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicket-contrib-openlayers/src/main/java/org/wicketstuff/openlayers/wicket-openlayersmap.js

Use the wicket namespace for a cleaner approach(like above), and remember to place your data in an array, so you can have multiple of the same components on the same page. Like so:


var Wicket;
if (!Wicket) {
Wicket = {};
} else {
if (typeof Wicket != "object") {
throw new Error("Wicket already exists and is not an object");
}
}
Wicket.omaps = {};
function WicketOMap(id, options) {
Wicket.omaps[id] = this;
}

Lots of dynamic stuff?

If you have lots of dynamic stuff you can use a texttemplate to interpolate your variables with it works really smooth, heres an example:


...
HashMap variables = new HashMap();
variables.put("alert", "helloworld");
TextTemplate textTemplate=new TextTemplate();
textTemplate.interpolate(variables);
String js= textTemplate.asString();

corrosponding java script, notice the template signature ${…}

alert("${alert}");

So above code will produce a javascript string ‘alert(“hello world”)’ very useful.

Using a behaviour

Behaviours are nice if you need some special that modifies the component you want to add too. It’s an easy way of getting information like markupid etc. Its good because you can access the component that you bind to, so you may put in javascript, add attributemodifiers etc for it.

Virtual tour of Mootips

Heres a virtual tour of Mootips javascript integration

go here for the minis wiki





Screencast: introducing Wicketstuff Iolite

4 09 2008

So without further delay watch the screencast below:





Doing Screen casts

3 09 2008

Doing a screen cast aren’t that hard, theres a lot of software out there, but you have to pay for it. For around 90$ you can get Screenflow, mac only for less you can get snapzshots which are both for mac and windows. Just remember to clean up your desktop, or use an extra monitor to record from.

However an really really important thing to note are whats the purpose of your screencast, do you need people to actually see what you are doing on screen like and command prompt etc? How will you share the screencast, there are lots of ways like google, youtube etc.. But they all convert your screencast into a lowever resolution. And in my case I need people to actually be able to see what I am doing. So how does one solve this? Well two ways, either record your screencast in a resolution closer to what it gets converted to, or host the screencast yourself.. Vimeo actually offers a hd solution for videos, it might be an option to preserve your screen cast at optimal resolution.

This is just some notes:

http://www.ffmpegx.com/flv.html

http://www.ffmpegx.com/video.html

http://www.ambrosiasw.com/forums/lofiversion/index.php/t60248.html

http://lists.apple.com/archives/QuickTime-Users/2005/Apr/msg00274.html

http://www.reelsmart.com/2008/02/14/vara-releases-screenflow-for-leopard/

http://www.macnn.com/articles/08/02/29/first.look.screenflow/

http://www.flip4mac.com/screenflow_features.htm





Wicket Iolite 0.3

3 09 2008

So it’s out just waiting to get built on the wicketstuff teamcity server, and be made public available from there.

Wicket Iolite are a Wicketstuff project, and it’s all about making development really easy for you. It’s a archetype that setups a project for you with a two module struture web and core. In core you will find JPA entities, and in wicket you’ll find the counter wicket part.

Changes(lots):

  • Depends on domdridges project
  • Real maven archetype
  • Lots of cleaning
  • Even more simple than before

Read more here:

http://wicketstuff.org/confluence/display/STUFFWIKI/Wicket-Iolite





Making a Maven Archetype

3 09 2008

So I want to create a maven archetype. My first run at this were a couple of months ago, it were pretty hard but then again I built the archetype from scratch.

I use userlist’s a lot so and though that it were very awkward how I did the previous archetype. So I wrote maven user list asking and theres actually a maven goal for it. So you can create an archetype in 6 steps:

  1. Build a project that will act as a template for the archetype
  2. run mvn archetype:create-from-project , from the project folder
  3. Edit the generated archetype ( placed in target/generated-sources/archetype ), it might not pickup on everything that needs to be substituted.
  4. From target/generated-sources/archetype of the project template run mvn install
  5. Try the archetype yourself by running mvn archetype:generate -DarchetypeCatalog=local from a fresh directory
  6. Repeat the process until satisfied

Now this also works for projects consistent of modules, a project structure like below:

Root
|-Core
|-Web

Happy Archetyping:)





Pump your Java with Caching

25 08 2008

So you want caching. First thing to see are if your application are applicable for it. There’s the 80/20 rule saying that you need to be maximum 20% writing on what you intend to cache, if you deviate too much from these numbers caching stuff could actually slow you down. I had some fun with this on my own “production” machine an old p3 500mhz (keep that in mind when you see results).

Im gonna write about my current stack which are Apache Http+Apache Tomcat, JPA / Hibernate + spring & Apache Wicket, this does’nt mean that you cant benefit from the ideas though if you arent using these frameworks, which leads me to what I believe are number one rule with caching:

Non intrusion , cache needs to be applied lightly in a non intrusive way

That way you can easily switch it off, switch strategies etc.

So with my stack you can actually introduce caching in each layer if you want to, i’ll start at Hibernate.

Caching with Hibernate

As I used Hibernate and my application seemed a bit heavy on the database I optimized everything, but Hibernate I thought lets start here. So I did, enabling the query cache and 2nd level cache were actually very simple and few lines of code. But this approach were very intrusive as the application needed to know about the caching mechanism, I went ahead any how. I spent 2 days pondering why it did not work, I kept getting cache misses even though I saw that the queries were added to the cache. Hibernate forum werent being responsive so I thought maybe theres another way. Which leads me to next thing.

btw I just bought Java Persitence with Hibernate http://www.manning.com/bauer2/ to help me digg into the cache with Hibernate.

Caching with Spring modules cache

So the spring guys has an non intrusive way of applying caching. It’s really simple :

ApplicationContext.xml add:

<import resource="classpath:cacheContext.xml" />

cacheContext.xml :

<?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:ehcache="http://www.springmodules.org/schema/ehcache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">

  [4]<ehcache:config failQuietly="true"
configLocation="classpath:ehcache.xml"/>

    <bean id="myCacheKeyGenerator" class="zeuzgroup.core.cache.ZeuzCacheKeyGenerator"/>
    <bean id="myCachingListener" class="zeuzgroup.core.cache.ZeuzCachingListener"/>

    <ehcache:methodMapInterceptors
            cachingInterceptorId="cachingInterceptor"
            flushingInterceptorId="flushingInterceptor">

        <ehcache:cacheKeyGenerator refId="myCacheKeyGenerator"/>

        <ehcache:cachingListeners>
            <ehcache:cachingListener refId="myCachingListener"/>
        </ehcache:cachingListeners>

[1]<ehcache:caching cacheName="translationCache"
methodFQN="zeuzgroup.core.localization.ITranslationService.get*"/>

<!--  Flush cache -->
    [2]<ehcache:flushing cacheNames="translationCache" methodFQN="zeuzgroup.core.localization.ITranslationService.put*" when="after"/>
    </ehcache:methodMapInterceptors>

    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <list>
               [3] <idref bean="translations"/>
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <value>cachingInterceptor</value>
                <value>flushingInterceptor</value>
            </list>
        </property>
    </bean>
</beans>
ehcache.xml
  1. setup target methods to cache
  2. setup which metods that evict cache
  3. point at beans to look in
  4. point at ehcache.xml

As you can notice theres two beans further more defined(myCachinglistener and mycachingkeygenerator), you can just use the default implementation provided. Although you might want to use your own keygenerator if using datetime properties in your objects, if your methods return objects with new stamps your cache will not be hit. In my setup my wicket page went from 12s to display to 4s (having a 2s round trip).

ehcache.xml

<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="1000" eternal="false"
 timeToIdleSeconds="0" timeToLiveSeconds="500" overflowToDisk="true"
 diskPersistent="false" diskExpiryThreadIntervalSeconds="500" />
 <cache name="translationCache" maxElementsInMemory="75000"
eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false"
diskPersistent="false"
 diskExpiryThreadIntervalSeconds="3600" />

Above are also pretty straight forward.. Now onto the next part.

Caching with Wicket, or preparation for web cache.

Caching statefull pages? Well you can. But remember that if you do when others look at the page you cache they’ll get the same result. Please remember that you cant cache pages with ajax on (AFAIK).

So this means that if you have a “simple” solution where you have users that can be either authorized or not it’s pretty straight forward. I went ahead and chose all the pages where my users arent logged in to be cachable. I decided to go with ehcache’s web cache namely the simplefiltercache. And to make it visible for the cache when a page could be cachable I added a noop parameter to all my pages called cache it has the value true. The simplest way to work with a cache are using urls, you might be able to do something http codes and cache all that does not sets the cache control header. But that’s stretching it to far for me.

Code:

public abstract class MyPage extends WebPage {
public static final String CACHEABLE = "cache";

private PageParameters myPageParameters;
[1]    public Boolean canCache() {

        if (MySession.class.isInstance(this.getSession())) {
            MySession mySession = (MySession) this.getSession();
            return !mySession.isAuthorized();
        }
        return true;
    }
    public MyPage(PageParameters pageParameters) {
[2]	myPageParameters = pageParameters;
[3]        BookmarkablePageLink creditsLink = new BookmarkablePageLink("credits",
                CreditsPage.class, getPageParameters(getSession().getLocale()));
        add(creditsLink);
}
[4]   protected PageParameters getPageParameters(Locale locale) {
        PageParameters pageParameters = new PageParameters();
        if (canCache() && !pageParameters.containsKey(CACHEABLE)) {
            pageParameters.add(CACHEABLE, "true");
        }
        if (!canCache()) {
            pageParameters.remove(CACHEABLE);
        }
        if (zeuzPageParameters != null) {
            pageParameters.putAll(zeuzPageParameters);
            if (pageParameters.containsKey("locale")) {
                pageParameters.remove("locale");
            }
        }

        pageParameters.add("locale", locale.getLanguage());
        return pageParameters;

}
Okay so 4 simple steps are needed to make our wicket pages cachable:

  1. Make a method that can determine if a page are cachable or not
  2. Keep a reference to the page parameters the page were initialized with.
  3. Use bookmarkablePageLink’s so that url’s are stable
  4. This is where the magic are done, add the cachable parameter to appropriate pages, notice that if you have a multilingual application you need that as a parameter otherwise the locale of the pages will be the one that last caused a miss.

Note : I had to set this to get stable parameter positions in urls:

        // Be able to sort page parametes
        UnitTestSettings.setSortUrlParameters(true);

Okay so now our wicket pages can be cached, now we just setup the cache:

add in ehcache.xml

<cache name=”SimplePageCachingFilter” overflowToDisk=”true” maxElementsInMemory=”500″ timeToLiveSeconds=”86400″ timeToIdleSeconds=”43200″/>

if you want define flush methods in cacheContex.xml:

    <ehcache:flushing cacheNames="SimplePageCachingFilter" methodFQN="zeuzgroup.core.provider.IDBDao.persistExercise*" when="after"/>

For me this made the page I talked about earlier go from 4s to 0.2s to display.

Conclusion

So I tried several approaches before comming to the approach showed above (regarding wicket). I tried creating a custom a IRequestEncodingStrategy, did’nt work for me but it’s my fault nothing todo with wicket. Sometimes simple are better I guess. An annoying thing were that apparently that my pages when in danish locale were’nt encoded with html entities (this caused chars like æ ø å to get corrupted), i’ve submitted a patch to wicket to support this http://issues.apache.org/jira/browse/WICKET-1795 , it’s just for component though a general setting would be nice. I think above are pretty straight forward, but of course it would be nice if wicket support something like it out of the box, but then again it requires many thing that only you as the developer can decide. Using above approach you’re free to chose ehwebcachefilter like i did or something else like Apache http, if you dont select ehcache, you’ll loose the evict option. But there might be other options. The above approach should be usable with other web frameworks aswell.





Wicket in Action, go get it

19 08 2008

So the book are finally out. I’ve been using the MEAP early access program reading the chapters as they came out. I deem myself to have a fair knowledge of wicket, but as it are self learned there are some gaps that needs to be closed. There were no books on wicket back in 2005 when I first got into wicket, it had a pretty steep learning curve for me, comming from a JSP and .net background I had to unlearn a lot of stuff to finally let go and ride the Wicket wave. Wicket in action closes these gaps nicely for me.

Wicket in Action really takes you softly through the cheeser application and at the end places you with an production ready application. This greatly softens the learning curve.

So what could be missing? Well for a beginner book nothing. If you pick it up for advanced use I’d liked to seen some more about creating your own ajax components, and howto create your own IRequestCodingStrategy to append a keyword to be able to cache with something like Apache Http server. But these are pretty advanced topics and probably not something you would stumple into.

So my advice are go buy the book, advanced or beginner it’ll certainly help you a lot and for the low price (maybe too low for such a great work) Manning are selling it for there are really no reason why not to Buy it.

For me it glues the areas of web development with Apache Wicket together and gives a great overview of Apache Wicket…it will make a great compendium.