Fork me on Github s

Posts Tagged java

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

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

Sweet JavaFX App on the Winter Olympics Website

Though it may be old news for people following JavaFX closely, I have just run across the JavaFX application on the Winter Olympics website.  Slick transitions and useful data make this a great example of what JavaFX can do.  I think it’s really cool that you can look at past olympics as well as the current year.

Maybe this will help generate a little buzz around JavaFX.

Check out the application on vancouver2010.com

Bookmark and Share

Tags: ,

2 Comments

Spring MVC Gotcha: Passing Response into Controller Method

I have a confession to make. I created this blog to not only help people out, or opine about industry topics, but as a personal scratch pad for me to help remember stuff. So with that in mind, I am going to take a personal note of a problem I had been dealing with.

Most of us using Spring MVC are familiar with the following:

   class SomeController {

     @RequestMapping("/action")
     public void action(HttpServletRequest request) {
       // do something
     }
   }

Simple, right? Annotation-mapped controller which will use the RequestMapping annotation to determine the viewName. Confused? Check this out. But, what happens when you decide to set a cookie in the action method? For this we will need access to the HttpServletResponse object. No problem, since Spring will automagically inject it into our method.

Observe the following:

   class SomeController {

     @RequestMapping("/action")
     public void action(HttpServletRequest request, HttpServletResponse response) {
       // add cookie using response.setCookie(Cookie) method
     }
   }

Looks good to me. Only problem is, it will not work (a small problem). Apparently, the Spring Framework assumes you are handling the response if it passes it into a method with a return type of void. This is because there is no good way for it to know if you did or didn’t.

No big deal, we can use a string to prevent this behavior:

   class SomeController {

     @RequestMapping("/action")
     public String action(HttpServletRequest request, HttpServletResponse response) {
       // add cookie using response.setCookie(Cookie) method
       return "action";
     }
   }

This will fix the problem. Consult the documentation here for more information.

Bookmark and Share

Tags: , , ,

2 Comments