A good way to stay flexible is to write less code. --Pragmatic Programmer

November 29, 2011

Development, Java, Web

(No comments)

In the company I work in we have some complex tags that are not easily unit-testable because there are some dependencies between them, the best option here should be to re-factor them, unfortunately as this would break backward compatibility, we have a process of deprecation to go through until we can actually do that.

But code with hardly any tests on them always makes me feel uncomfortable. so I decided to do some (almost integration) tests but running as part of the normal unit test suite
I’m doing this by placing the tags on a jsp, running this on a embedded Jetty Server and using Selenium Webdriver to test the resulting html.

First the base class, which takes care of starting/stopping the embedded Jetty Server and setting up the web driver.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public abstract class BaseTest {
    private static int port = 9595;
    private static Server server = new Server(port);
 
    protected static String baseUrl = "http://localhost:" + port + "/";
    protected static WebDriver driver;
 
    @BeforeClass
    public static void setup() throws Exception {
 
        //configure jetty as an exploded war
        URL webAppUrl = BaseTest.class.getClassLoader().getResource("/");
        WebAppContext wac = new WebAppContext();
        wac.setContextPath("/");
        wac.setWar(webAppUrl.toExternalForm());
 
        server.setHandler(wac);
        server.setStopAtShutdown(true); //makes sure the sever is stopped even if the @AfterClass is never reached
        server.start();
 
        //HtmlUnit drive doesn't give a popup, the rest of the drivers do
        driver = new HtmlUnitDriver();
    }
 
    @AfterClass
    public static void teardown() throws Exception {
        driver.close();
        server.stop();
    }

In my project I have setup a resources directory that contains a WEB-INF/ with a web.xml containing my custom tag definitions and my tld file as you would with a normal web project
Webdriver comes with a set of Drivers for different browsers (Firefox, chrome, IE, iPhone, Android, etc) for testing browser compatibility, I don’t care about that, the tags I’m testing do not output any html/css that might require this.
The HtmlUnit driver is internal and doesn’t popup a browser window so ideal for my purpose.

Writing a test now becomes very easy:

In this case I have a custom tag that when invoked simply outputs “Hello World”

my test jsp:

1
2
3
4
5
6
7
8
9
10
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"  isELIgnored="false" %>
<%@ taglib uri="/customtaglib" prefix="custom" %>
<html>
  <head>
    <title>Hello World</title>
  </head>        
  <body>
    <p><custom:helloworld /></p>
  </body>
</html>

The Test class:

1
2
3
4
5
6
7
8
9
10
public class HelloWorldTest extends BaseTest {
 
    @Test
    public void testHelloWorldTag() {
        driver.get(baseUrl + "helloworld.jsp");
        Assert.assertEquals("Hello World", driver.getTitle());
 
        WebElement element = driver.findElement(By.cssSelector("body p"));
        Assert.assertEquals("Hello World", element.getText());
    }

Testing the resulting html is made very easy, by having the WebElement findElement() and List findElements() methods.
and then setting predicates with the By class. for instance By.cssSelector(), By.tagName() etc.
It is also possible to test click throughs and form submits, by calling click() or submit() on WebElements.

Added bonus is that although the tag code is running in the embedded jetty server and not in the unit tests itself it’s coverage is measured by our code coverage tools

One thing to look out for is for the embedded Jetty to work with JSP’s you need to add jetty’s version of the jsp spec to your project not the javax.servlet.* ones.
my maven dependencies look likes this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty</artifactId>
            <version>6.1.22</version>
        </dependency>
        <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jsp-api-2.1</artifactId>
            <version>6.1.14</version>
        </dependency>
         <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jsp-2.1</artifactId>
            <version>6.1.14</version>
        </dependency>
        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.7</version>
             <scope>test</scope>
        </dependency>
    </dependencies>

December 17, 2009

Development, Java

Comments Off

I’ve been playing around with REST (REpresentational State Transfer) for a bit and decided to write a small tutorial to show how easy it is to create a rest interface to your business objects

Advantages of rest

  • Works over HTTP, known protocol with known data formats (mime types), no weird ports open in your firewall
  • Every resource is uniquely identified by a URI
  • Can do CRUD on those resources (they are just called POST, GET, PUT, DELETE)
  • used by all the major players for cloud applications (SUN’s cloudApi, Microsoft’s Azure services platform)
  • we might finally get rid of webdav

I’ll be using the Jersey Framework for this.
As i’ve been working on a backend that will allow you to manage agile development processes (Scrum, Kanban etc) I thought I use that.

In this application every object is represented by a Card for instance a Story, Task, Bug, work Item, etc.
Cards have a hierarchical structure and can each have custom properties
The class looks something like this (removed methods for clarity):

public abstract class Card {
	private long id;
	private List children = new ArrayList();
	private List properties = new ArrayList()
}

and then for instance the Story class with some default values set in the constructor:

public class Story extends Card {
	public Story() {
		addProperty("Title", "A new story");
		addProperty("Description", "as a .. I want .. for the benefit of ..");
		addProperty("Storypoints", "0");
	}
}

To be able to return these objects through REST they need to be in a format that can be distributed over HTTP, in this case we will be using XML and JSON.
The Java XML Bindings are perfectly suited to create xml representations of our classes

@XmlRootElement(name="card")
public abstract class Card {
	private long id;
 
	@XmlAttribute(name="type")
	protected String instance = this.getClass().getSimpleName();
 
	@XmlElement(name="card")
	private List children = new ArrayList();
 
	@XmlElement(name="property")
	private List properties = new ArrayList();
 
	@XmlAttribute
	public long getId() {}
}

* the Entry class is a simple class with a name and value property, I choose this approach as JAXB has an issue in representing HashMaps() in XML
this will produce the following xml

 

for JSON we don’t need to do anything special then include the jersey-json.jar to the project.

Now to configure and hookup the rest servlet
I added the jersey servlet to my web.xml

    	Rest Web Service
    	com.sun.jersey.spi.container.servlet.ServletContainer
    	1
 
    	Rest Web Service
    	/services/*

And create the service provider class

@PerRequest
@Path("/agileassistant")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class AgileAssistantService {
 ...
}

This will tell Jersey that this is a provider that will respond to requests to /rest/agileassistant, accept JSON and XML and can output JSON or XML depending on the accept headers sent by the client

Now if we for instance want to return the first card (rootCard) and all its children we add this method

	public static Card rootCard = Card.createCard(Root.class);
 
	@GET
	public Card getRoot() {
		return rootCard;
	}

(in my data model the rootCard is always present and functions as a starting point to add the rest of the cards in a hierarchical structure)
So requesting this card will effectively return the entire structure for my test data:

 

Doing a parameterized query is almost as easy

	@GET
	@Path("/card/{id}")
	public Card getCard(@PathParam("id") long id) {
		return getCardById(rootCard, id);
	}

here the id that you specify will be injected into the parameter
giving the following output

 

To conclude enabling rest for your applications is pretty easy, writing this blog took longer than writing the code.
In a next post I will add POST/PUT/DELETE requests to store data in your application

November 26, 2009

Development, Java, JavaFX

Comments Off

Data binding in JavaFX is pretty straightforward.
You should think binding to Java Objects should be just as simple, well it is a little complicater then just doing

var someObject : bind myJavaclass.getProperty();

JavaFX needs to be aware of any changes to the bound variables to be able to update the related objects. It does this automagically for all javafx objects.
It seems JavaFX uses the Observer/Observable pattern for all its internal objects, well we can do the same to bind with JavaObjects.
To get myself familiar with JavaFX i decided to write a photoviewer/editor. This application has a java backend with in particular a Photo class which contains all the information of a certain picture, filename, path, tags, exif information etcetera

To get changes in the Java class to appear in the gui I create a PhotoAdapter javafx class that extends Observer and implemented the properties I need in my GUI.

public class PhotoAdapter extends Observer {
    public-read var filename: String;
    public-read var tags: String[];
    public-read var exif: String[];
 
    public-init var photo: Photo
         on replace {
            photo.addObserver(this);
            filename=photo.getFilename();
            tags = photo.getTags();
            exif = photo.getExif();
         };
 
    override function update(observable: Observable, arg: Object) {
        filename = photo.getFilename();
        tags = photo.getTags();
        exif = photo.getExif();
    }

after that I had my existing Java Photo class extend Observable and in every method that made changes I added the methods setChanged() and NotifyObservers() to inform the Observers about the change

public class Photo extends Observable {
    private Map<String, String> exifInformation; 
    ....
    public void setExifInformation(Map exifInfo) {
        this.exifInformation = exifInfo;
        setChanged();
        notifyObservers();
    }
}

in my main javafx class I can then use it as follows

    var photoAdapter = PhotoAdapter {
        photo : new Photo(startImage);
}

and use to fill a ListView swing object with for instance the tags:

    ListView {
        items:     bind photoAdapter.tags;
        width:     200;
        height:    300;
    }

et viola, thats all that there is to it

November 11, 2009

Development, Java

Comments Off

As I’m working as a Java developer in a microsoft oriented company this means I sometime have to do .Net programming.
As there are some things I don’t like about .Net (no checked exceptions is one) there is one thing I find very good and useful.

In .Net an object that implements the IDisposable interface can be initiated with the Using command like this:

using (TextWriter w = File.CreateText("log.txt"))
    { w.WriteLine("This is line one");
}

After the block has executed, using will take care of closing the writer and freeing the resources.
This gives me solid readable code without memoryleaks.

Now looking at Java, closing resources usually involves putting a close() in a finally block, with another try-catch construction to catch exceptions that the close() can throw.
this is ugly, errorprone and can obfuscate the real exception that happened.

Java 7 comes to the rescue, one of the approved proposals for java 7 is “automatic resource management”
the following code block will demonstrate this

static void copy(String src, String dest) throws IOException {
   try (InputStream in = new FileInputStream(src); 
         OutputStream out = new FileOutputStream(dest)) {
 
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
        out.write(buf, 0, n);
    }
    //optional catch block
    //optional finally block
}

In Java 6 or lower the above code would contain 2 try-finally blocks to handle closing the input and ouput streams, another 2 try-catch blocks to handle exceptions from the close() commands, and more catches for exceptions you would want to handle specifically

Off all the features in java 7 this is the one I’m looking forward the most, the forkjoin and invokeDynamic changes following close though.
here is a list of all the features in java 7
http://openjdk.java.net/projects/jdk7/features/