Fork me on Github s

Intercept method calls in Groovy for automatic type conversion

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!

Bookmark and Share

Tags: ,

No Comments

Absent Code attribute in method that is not native or abstract

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.

Bookmark and Share

Tags: ,

No Comments

Naming your unit tests

When you create a test for your class, what kind of naming convention do you use for the tests? How thorough are your tests? I have lately switched from the conventional camel case test names to lower case letters with underscores. I have found this increases the readability and causes me to write better tests.

A simple utility class:


public class ArrayUtils {

  public static < T > T[] gimmeASlice(T[] anArray, Integer start, Integer end) {
    // implementation (feeling lazy today)
  }

}

I have seen some people who would write a test like this:


public class ArrayUtilsTest {

  @Test
  public void testGimmeASliceMethod() {
    // do some tests
  }
}

A more thorough and readable test would be:

public class ArrayUtilsTest {

  @Test
  public void gimmeASlice_returns_appropriate_slice() {
    // ...
  }

  @Test
  public void gimmeASlice_throws_NullPointerException_when_passed_null() {
    // ...
  }

  @Test
  public void gimmeASlice_returns_end_of_array_when_slice_is_partly_out_of_bounds() {
   // ...
  }

  @Test
  public void gimmeASlice_returns_empty_array_when_slice_is_completely_out_of_bounds() {
    // ...
  }
}

Looking at this test, you have no doubt what the method is supposed to do. And, when one fails, you will know exactly what the issue is.

Bookmark and Share

Tags: , , ,

No Comments

Using runtime generic type reflection to build a smarter DAO

Have you ever wished you could get the runtime type of your generic class? I wonder why they didn’t put this in the language. It is possible, however, with reflection:

Consider a data access object (DAO) (note: I had to use brackets b/c the arrows were messing with wordpress):

public interface Identifiable {

   public Long getId();

}

public interface Dao< T extends Identifiable > {

  public T findById(Long id);

  public void save(T obj);

  public void delete(T obj);

}

Using reflection, we can create a DAO implementation base class, HibernateDao, that will work for any object:


import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

public class HibernateDao< T extends Identifiable> implements Dao< T > {

  private final Class clazz;

  public HibernateDao(Session session) {
    // the magic
    ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
    return (Class) parameterizedType.getActualTypeArguments()[0];
  }

  public T findById(Long id) {
    return session.get(clazz, id);
  }

  public void save(T obj) {
    session.saveOrUpdate(obj);
  }

  public void delete(T obj) {
    session.delete(obj);
  }
}

Then, all we have to do is extend from the class:

public class BookDaoHibernateImpl extends HibernateDao< Book > {

}
Bookmark and Share

Tags: , ,

No Comments

Subscribe to gooder code via email!

I have added a new feature to the blog.  Email subscriptions! 

If you signup using the form on the right rail, you will receive email notifications when I make a new post.  These are delivered by Feedburner.  So signup, it’s fast, and convenient.

And if you are reading this post in your email reader, thanks for signing up!

Bookmark and Share
No Comments

Javascript Syntax Highlighter

I just want to do a quick shout out to Alex Gorbatchev for his most excellent Javascript syntax highlighter.  I installed it to the blog and am very happy about it.  You can now hover over code snippets and copy+paste, view, or print the code.

So, if you have a blog or other use for it, I highly recommend it.

Bookmark and Share

Tags:

No Comments

Quit your shitty job!

As a developer, what happens when you are running late on a deadline?  Do you work late for more pay?  Do you get chewed out?  What happens if a feature fails to deliver the business value that was expected?  Is it your responsibility?

Too often in the software development industry this is the case.  Developers are not given the respect afforded other professionals.  Instead, there is a perception that they are underperforming, lacking skills, or irresponsible.  There is no concept of total team effort.

What is total team effort?

What if, instead of blaming the developers, missed deadlines are the result of a failure in planning, or a lack of resources?  The failure needs to be identified, and corrected in a respectful manner.  Only then can you take corrective measures to insure it doesn’t happen again.  Does your company have a process for regularly analyzing workflow? 

I recently had a job interview with a company where the representative practically bragged about making their developers work long hours under duress.  This is not an environment I care to subject myself to.  Nor would any other talented developers that I know.  Who suffers?  The business suffers.  Product development suffers.  When we fail to deliver value to the business on a regular basis, they start to question our worth.  It’s a cyclical, self-feeding trend.  One that I don’t want to be a part of, and you shouldn’t either.

Bookmark and Share

Tags: ,

3 Comments

Using Cucumber tests with Maven and Java

Want to jump right in? I have zipped up a working project, with examples. You can download it here.

What’s that? You like using Cucumber and want to use it with your Java project but your company ecosystem is not hip to JRuby?  Enter the cukes4duke project, which allows you to run cucumber with most JVM-based languages.  I am focusing on running it with the Maven plugin. This tutorial assumes you have maven installed, and Java knowledge.

Before you start, you must run the following goal. It will install JRuby and the gems to your .m2 repository.

mvn -Dcucumber.installGems=true cuke4duke:cucumber

Then add the following to your pom:

    
        
            codehaus
            http://repository.codehaus.org
        
        
            cukes
            http://cukes.info/maven
        
    


            cukes
            http://cukes.info/maven
        
    

        0.3.2
    

    
        
            cuke4duke
            cuke4duke
            ${cuke4duke.version}
            test
        
        
            org.picocontainer
            picocontainer
            2.8.3
            test
        
        
            junit
            junit
            4.8.1
            test
        
    

    


                cuke4duke
                cuke4duke-maven-plugin
                ${cuke4duke.version}
                
                    
                        
                  -Dcuke4duke.objectFactory=cuke4duke.internal.jvmclass.PicoFactory
                        
                        ${cucumber.debug}
                    
                    
                        ${basedir}/target/test-classes
                        --tags ~@wip
                    
                    
                        install cuke4duke --version ${cuke4duke.version}
                    
                
                
                    
                        run-features
integration-test
                        
                            cucumber
                        
                    
                
            

                org.apache.maven.plugins
                maven-compiler-plugin
                2.0.2
                
                    1.6
                    1.6
                
            
        
    

Next, create a feature file under the ‘features’ directory (at the root of your project).

features/example.feature:

Feature: Example of a feature file
  As some aspiring cuke4duke user
  I want an example of how it works
  So that I can easily setup my project to use it

  # This should pass
  Scenario: A simple passing scenario
    Given the letter 'A'
    When I check the letter
    Then the letter should be 'A'

Then, create a ’step’ class under src/test/java/cukes:

src/test/java/cukes/CukeSteps.java:

package cukes;

import cuke4duke.annotation.I18n.EN.Given;
import cuke4duke.annotation.I18n.EN.Then;
import cuke4duke.annotation.I18n.EN.When;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

public class CukeSteps {

    private char theLetter;

    @Given("^the letter '([A-Za-z])'$")
    public void gimmeALetter(final char theLetter) {
        this.theLetter = theLetter;
    }

    @When("^I check the letter(?:s)?$")
    public void checkThem() {
        // just a stub
    }

    @Then("^the letter should be '([A-Za-z])'$")
    public void checkTheLetter(final char aLetter) {
        assertThat(theLetter, is(aLetter));
    }
}

Now, run that test using:

mvn integration-test

I have zipped up an example project with more example steps. It is located here.

Bookmark and Share

Tags: , ,

5 Comments

Does Your Build Suck?

I have come up with a few questions you should ask yourself if your build is up to snuff. 

  • Does it take longer than 10 minutes to setup a new computer to build a project?
  • Are there only a one or two people who know how to completely setup a new computer?
  • Do builds sometimes fail on the integration server when they are passing on your development machine?
  • Do you often make cross-repository commits?
  • Does building a subproject force you to build several other subprojects?
  • Does it take longer than 2 minutes to checkout a new project and build it successfully?
  • Is it possible for other developers (or other external factors) to break your development build without checking in code?
  • Can you use any IDE with your project?

If you answered yes to any of these questions, perhaps you should spend some time refactoring your build and/or project structure.  A nasty build can be very frustrating for developers yet is an oft overlooked part of development.

Bookmark and Share

Tags: , , , , , ,

1 Comment

Extending Currying: Partial Functions in Javascript

Last week I posted about function currying in javascript.  This week I am taking it a step further by adding the ability to call partial functions.

Suppose we have a graphing application that will pull data via Ajax and perform some calculation to update a graph.  Using a method with the signature ‘updateGraph(id,value)’.

To do this, we have do something like this:


for(var i=0; i < things.length; i++) {
  Ajax.request('/some/data', {id: things[i].id}, function(json) {
    updateGraph(json.id, json.value);
  });
}

This works fine.  But, using this method we need to return the id in the json response from the server.  This works fine, but is not that elegant and increase network traffic.

Using partial function currying we can bind the id parameter and add the second parameter later (when returning from the asynchronous call).  To do this, we will need the updated curry method.  I have added support for sending additional parameters at runtime for curried methods.

Function.prototype.curry = function(scope) {
  scope = scope || window;
  var args = [];
  for (var i=1, len = arguments.length; i < len; ++i) {
    args.push(arguments[i]);
  }
  var m = this;
  return function() {
    for (var i=0, len = arguments.length; i < len; ++i) {
      args.push(arguments[i]);
    }
    return m.apply(scope, args);
  };
}

As you can see, partial currying gives is a very useful tool and this simple method should be a part of every developer’s toolbox.

Bookmark and Share

Tags:

No Comments