Fork me on Github s

Archive for category Lessons

Using Java classes in JRuby

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

Tags: ,

1 Comment

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!

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.

Tags: ,

1 Comment

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.

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 > {

}

Tags: , ,

1 Comment

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.

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.

Tags: , ,

37 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.

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.

Tags:

No Comments

On Contract Employment

I am going to post about something I don’t post about a lot, the business side of development.  Scott at the antipimp does a good job of explaining how contracts work from a business perspective.  I am going to give a view from the ground.

First, a little background on myself.  I have recently taken a 6 month contract after about 8 years of fulltime employment.  I have 2 kids, and a stay at home wife.  I took this contract opportunity because I wanted to try it on for size.  I have always wondered whether I would like doing contracts over fulltime employment.  So, in keeping with the theme of this blog I will write this down now so that I may reference it later.

  1. ALL jobs are temporary!
    Right now you may not realize it, most people simply ignore it, but EVERY job is temporary.  Everyone should be planning for life after the money stops coming in.  Sadly, most people do not.  Contracting pushes this issue to the forefront, making you deal with it.  After a month on a contract, I am happy to say that I am saving more than I ever saved in a fulltime position.  Hopefully, I will be ready in case of an extended window of unemployment between contracts.
  2. Networking
    I find it extremely gratifying getting to know people.  It is especially beneficial when moving to a new city.  What better way to go out and meet people in your field than to work a few contracts?  6 months of working beside someone and you get to know them pretty well.  This is one of my favorite aspects.
  3. Technical Agility
    Moving between IS shops takes (or molds you into) a flexible person.  You have to be able to go in and hit the ground running.  This means you need to be able to sit down and start work on a large codebase working in a language that you may or may not have that much experience in.  It is also an excellent way to learn new languages and broaden your technical skill set.  I took my current position to learn Ruby.  A month ago, I had only used it in passing, but now I am using it every day.  It’s a tragedy in this field when people start coding for the joy and love of coding, then become deeply entrenched in their companies methods and technologies that it becomes a just a job.
  4. Less Stress
    I am not talking about the kind of stress you get from a jackass boss.  I am talking about the kind of stress I (or others) experience about planning and future proofing your code.  Not saying I stay up at night worrying whether we have done it right, if that code I wrote today is going to bite me later, but it still creeps around in the dark recesses of my mind.  Careful though, I am not suggesting you write sloppy code; just defer any large architectural or design decisions to the ‘code owners’.
  5. Flexible Scheduling
    It makes me very happy to be able to cut out a few hours early on a Friday (provided the work is done) and start the weekend off early by going to the pool, or taking the kids to the park.  Contracting provides you this opportunity (mileage may vary).  Most of your fulltime brethren will not care, they will be jealous that they’re corporate policy prevents them from doing the same.  However, you must be mindful of situations where this is not appropriate, and don’t over do it.  You are there to work after all.
  6. Affirmation of Need
    Have you ever been stuck in a job where you thought you were underpaid?  Have you ever been in a position where you felt like there was not enough workload for you?  This is not a problem for contractors.  When you start a contract it is understood that you are needed, and the employer knows that you are happy with the terms.

Contracting may not be for everyone.  But, if you develop a relationship with a good consulting firm, keep their clients happy, then they will keep you happy.  They want you to work almost as much as you do.  Just be sure and plan financially for any windows of unemployment.

Tags:

No Comments