I recently came across an interesting question on stack overflow with some interesting reponses. I like this post for three reasons. First, I am a big fan of dependency injection, it forces you to decouple your code, create cohesive interfaces, and should result in testable classes. Second, the author took the approach I usually do when trying to evaluate a technique or technology; suspend personal feelings and try to find some compelling arguments against it. Third, it proved that it is very difficult to come up with a compelling argument against dependency injection.
HtmlUnit is a great library for performing web integration tests in Java. But sometimes node traversal can be somewhat cumbersome. Fear not fellow automated tester (good for you!). I found a great little project on Github that will allow you to query your document for elements via css selectors similar to jQuery.
The project is located at https://github.com/chrsan/css-selectors. You can use Maven to build it, or download 1.0.2 here. Beware. I will not be updating this link so I suggest you download the latest code.
In any case, you can use it like so:
// from HtmlUnit getting started
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
final DOMNodeSelector cssSelector = new DOMNodeSelector(page.getDocumentElement());
final Set elements = cssSelector.querySelectorAll("div.section h2");
final Node first = elements.iterator().next();
assertThat(first.getTextContent(), equalTo("HtmlUnit"));
The only problem here is that the querySelectAll returns a Set<Node>. Not HtmlElement like we may want in some cases. However, if you were to reflect on the Set, you would find that it is indeed a Set of HtmlElement objects.
Typically, I like to create a base class for my web tests. Just for fun, I am using the $ method similar to jQuery.
public class WebTestBase {
protected WebClient webClient;
protected HtmlPage htmlPage;
protected void goTo(final String url){
return (HtmlPage)webClient.getPage(url);
}
protected List $(final String cssSelector) {
final DOMNodeSelector cssSelector = new DOMNodeSelector(htmlPage.getDocumentElement());
final Set nodes = cssSelector.querySelectorAll("div.section h2");
// for some reason Set cannot be cast to Set?
final List elements = new ArrayList(nodes.size());
for (final Node node : nodes) {
elements.add((HtmlElement)node);
}
return elements;
}
}
Now we can write tests like this:
public class LoginWebTest extends WebTestBase {
@Test
public void login_page_has_instructions() throws Exception {
goTo(baseUrl + "/login")
assertThat( $("p.instructions").size(), equalTo(1) );
}
}
I thought it might be a good idea to post some professional goals for 2011. Hopefully, I can look at this list at the end of the year and have accomplished most of them.
- Release an Android app to the marketplace – I figured I would put this first because I have one that I have been working on for a while and it is about ready. Along with this, I would like to start another one and continue to develop my Android skills.
- Contribute free software to the community – Again, I have an SMF plugin that will fill this requirement nicely. Just need to give it some polish and release it. That’s not all, I would like to add a few more libraries on github, or possibly contribute to an open source project.
- Regularly attend a user group meetings outside of Java – A great way to meet people and learn new things.
- Obtain the Oracle Certified Web Developer Certification – I got the SCJP a few years ago and would like to obtain another one. One step closer to Certified Enterprise Architect.
- Learn scala – As a language geek, I like to stick to the Pragmatic Programmer’s ‘learn a new language every year’ rule (last year was Ruby). Scala presents some new concepts all wrapped in a JVM-based OOP language. Time to dig in.
- Write an app using JSF – New JEE 6 features are pretty slick. I want to really leverage them in an app.
- Present at a user group meeting – Last but not least, I would like to improve my public speaking and skills in presenting. Also, is a great reason to dig in to some latest and greatest tech.
- Use git more, and more effectively – Trying to move all my personal projects from Subversion to Git.
That’s it. A little daunting, but I am confident I can at least touch on most of these and it’s a great roadmap to my professional development.
AJAX Loading Images
Dec 23
Using Java classes in JRuby
Nov 19
I needed to do some reflection today so I fired up interactive JRuby (jirb) to inspect a jar. Surprisingly, I couldn’t remember exactly how to use Java classes in JRuby. So I did some searching on the internet and found this to be a common question with many answers. So I figure I will document it here in case I forget how in the future.
Add it’s folder to the load path, require it, then use it!
$: << '/path/to/my/jars/' require 'myjar' # so we don't have to reference it absolutely every time (optional) include Java::com.goodercode my_object = SomeClass.new
Zune API Library for Ruby
Oct 26
Those of you who know me, know my favorite music player is the Zune.
For some reason it seems most of my spare time lately seems to be creating Zune API libraries for different languages (I have a PHP one as well). Here’s another one for Ruby! If you use it, let me know. I would love to hear what people are working on.
It’s hosted at github, and very easy to use.
zune_card = Zune::ZuneCard.for('a_zune_tag')
Checkout the README for deets on what fields the object will have.
Playing around with Sinatra the other day and realized I could really use something like this for Groovy. Thus, Graffiti was born. It’s basically a thin wrapper around Jetty. At first, I thought I might write my own server for it (everybody needs to do that once, don’t they?), but decided to invoke the ‘simplest thing that could possibly work’ principle.
Here is the requisite ‘Hello World’ example:
import graffiti.*
@Grab('com.goodercode:graffiti:1.0-SNAPSHOT')
@Get('/helloworld')
def hello() {
'Hello World'
}
Graffiti.serve this
The code, plus more documentation is hosted under my github account.
Zune API Library for Python
Sep 18
I am about to start working on a Python project for work. So I thought it was probably time to learn Python! This weekend I took on this task. I decided to rewrite a library I wrote in PHP to access Zune user data. I got it finished and decided to put it on github.
Usage is simple:
zuneCard = ZuneCard('ZuneTagHere')
You can access things like user information, favorites, recent plays, and most played. The properties are documented (pydoc, under /docs). So for the 1 other person that may use this, you’re welcome!
One of the cooler things you can do with groovy is automatic type conversion. If you want to convert an object to another type, many times all you have to do is invoke the ‘as’ keyword:
def letters = 'abcdefghijklmnopqrstuvwxyz' as List
But, what if you are wanting to do something a little fancier, like converting a String to a Date?
def christmas = '12-25-2010' as Date ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '12-25-2010' with class java.lang.String' to class 'java.util.Date'
No bueno!
I want to be able to do custom type conversions so that my application can do a simple String to Date conversion. Enter the metaMethod. You can intercept method calls in Groovy using the following method:
def intercept(name, params, closure) {
def original = from.metaClass.getMetaMethod(name, params)
from.metaClass[name] = { Class clazz ->
closure()
original.doMethodInvoke(delegate, clazz)
}
}
Using this method, and a little syntactic sugar, we create the following ‘Convert’ class:
// Convert.from( String ).to( Date ).using { }
class Convert {
private from
private to
private Convert(clazz) { from = clazz }
static def from(clazz) {
new Convert(clazz)
}
def to(clazz) {
to = clazz
return this
}
def using(closure) {
def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
from.metaClass.asType = { Class clazz ->
if( clazz == to ) {
closure.setProperty('value', delegate)
closure(delegate)
} else {
originalAsType.doMethodInvoke(delegate, clazz)
}
}
}
}
Now, we can make the following statement to add the automatic date conversion:
Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }
def christmas = '12-25-2010' as Date
Groovy baby!
I got the following, quite puzzling error today when running a unit test:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/http/Cookie
A google search found this post, which explains that it is caused by having an interface in the classpath, and not an actual implementation.
In this case it’s the java-ee interface. To fix this I added the jetty servlet api implementation to my pom:
jetty
javax.servlet
test
Piece of cake. I have run in to this before, so I figured I would capture the fix here in case I run in to it again.
s

