Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, April 7, 2011

Launch Configurations in Eclipse

In this post I point out where Eclipse is storing the launch configurations.

After a fresh install of my laptop I wanted to restore the launch configurations of Eclipse. After some searching I finally found the location. I am reporting it here for future reference.

The eclipse launch configurations can be found in your workspace at


.metadata/.plugins/org.eclipse.debug.core/.launches

Sunday, February 6, 2011

Parametrized Junit Tests: Postscript

In two earlier blog posts I commented on parametrized junit tests. This blog post will complement these post with an example of a piece of code.

Because all the important points are made in the other posts I will only present the Junit runner I created. A Maven project demonstrating this technique can be found code at my minimal examples repository

Without further ado: the Junit runner.

package org.junit.runners;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;

public class ParameterizedWithBuilder extends Suite
{
        private class TestClassRunnerForParametersWithBuilder extends BlockJUnit4ClassRunner
        {
                private final int fParameterSetNumber;

                private final List<Object> fParameterList;

                TestClassRunnerForParametersWithBuilder(Class<?> type, List<Object> parametersList, int i)
                        throws InitializationError
                {
                        super(type);
                        fParameterList = parametersList;
                        fParameterSetNumber = i;
                }

                @Override
                public Object createTest() throws Exception
                {
                        return getTestClass().getOnlyConstructor().newInstance(computeParams());
                }

                private Object computeParams() throws Exception
                {
                        try
                        {
                                return fParameterList.get(fParameterSetNumber);
                        }
                        catch (ClassCastException e)
                        {
                                throw new Exception(String.format("%s.%s() must return a Collection of objects.", getTestClass()
                                        .getName(), getParametersMethod(getTestClass()).getName()));
                        }
                }

                @Override
                protected String getName()
                {
                        return String.format("[%s]", fParameterSetNumber);
                }

                @Override
                protected String testName(final FrameworkMethod method)
                {
                        return String.format("%s[%s]", method.getName(), fParameterSetNumber);
                }

                @Override
                protected void validateConstructor(List<Throwable> errors)
                {
                        validateOnlyOneConstructor(errors);
                }

                @Override
                protected Statement classBlock(RunNotifier notifier)
                {
                        return childrenInvoker(notifier);
                }
        }

        private List<Runner> runners = new ArrayList<Runner>();

        public ParameterizedWithBuilder(Class<?> klass) throws Throwable
        {
                super(klass, Collections.<Runner> emptyList());
                List<Object> parametersList = getParametersList(getTestClass());
                for (int i = 0; i < parametersList.size(); i++)
                        runners.add(new TestClassRunnerForParametersWithBuilder(getTestClass().getJavaClass(), parametersList, i));

        }

        @Override
        protected List<Runner> getChildren()
        {
                return runners;
        }

        @SuppressWarnings("unchecked")
        private List<Object> getParametersList(TestClass testClass) throws Throwable
        {
                return (List<Object>) getParametersMethod(testClass).invokeExplosively(null);
        }

        private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception
        {
                List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
                for (FrameworkMethod each : methods)
                {
                        int modifiers = each.getMethod().getModifiers();
                        if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
                                return each;
                }

                throw new Exception("No public static parameters method on class " + testClass.getName());
        }

}

Sunday, January 30, 2011

Parametrized JUnit Tests Revisited

In the Parametrized JUnit Tests blog post I explained how to create a parametrized junit test. In this blog post I will discuss the reaction of one of my colleagues.

After reading my blog post about parametrized junit tests a colleague expressed his objections with this way of testing. He was a bit disappointed with one thing in particular. The signature of the public static method that is used to construct the test.

@Parameters
public static Collection<Object[]> data()

Is returns a collection of Object arrays. One Object array for each set of parameters. The reason this should be an Object array becomes clear from it's usage.

List<Object[]> data = new ArrayList<Object[]>();
data.add(new Object[] { 2, new Integer[] { 2 } });
return data;

Because the parameters used are of different type, in this case an Integer and an Integer array, they only super-type they have in common is Object.

The objection of my colleague was that is berefts the compiler of the oppertunity to detect type errors at compile time. The compiler would happily compile the following code. But it would blow up at run time.

List<Object[]> data = new ArrayList<Object[]>();
data.add(new Object[] { 2, new Integer[] { 2 } });
data.add(new Object[] { 2, new Double[] { 2.0 } });
return data;

After some discussion with my colleague we came up with the following solution. Instead of using a lot of parameters in the constructor, use only one. By using the builder pattern one retains the type information. Furthermore because now only one parameter is needed, the nearest super-type of all the parameters is the type of the parameter itself.

The code that follows show the same test as in the previous blog post. The change is reflected in the use of the builder pattern. Note that a fluent interface is used to easily construct a builder for the test.
One could still object that the array is now superfluous. They are correct. One way to deal with their objections is to write an custom runner.

@RunWith(Parameterized.class)
public class FactorizationTest
{
    private int number;

    private List<Integer> expectedResult;

    public FactorizationTest(FactorizationTestBuilder builder)
    {
        this.number = builder.getNumber();
        this.expectedResult = builder.getExpectedResult();
    }

    @Test
    public void factorize()
    {
        assertEquals(expectedResult, Factorization.factor(number));
    }

    @Parameters
    public static Collection<FactorizationTestBuilder[]> data()
    {
        List<FactorizationTestBuilder[]> data = new ArrayList<FactorizationTestBuilder[]>();
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(2).expect(2) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(8).expect(2, 2, 2) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(9).expect(3, 3) });
        data.add(new FactorizationTestBuilder[] { FactorizationTestBuilder.withNumber(72).expect(2, 2, 2, 3, 3) });
        return data;
      }
}

class FactorizationTestBuilder
{
    private int number;

    private List<Integer> expectedResult = new ArrayList<Integer>();

    public static FactorizationTestBuilder withNumber(int number)
    {
        return new FactorizationTestBuilder(number);
    }

    private FactorizationTestBuilder(int number)
    {
        this.number = number;
    }

    public FactorizationTestBuilder expect(Integer... expectedResult)
    {
        this.expectedResult = Arrays.asList(expectedResult);
        return this;
    }

    public int getNumber()
    {
        return number;
    }

    public List<Integer> getExpectedResult()
    {
        return expectedResult;
    }
}

In this blog post I described the objections of a colleague on the previous Parametrized Junit Test blog. I have shown had to meet these objections by using the builder pattern.

Saturday, January 15, 2011

Parametrized JUnit tests

In this post I will examine parametrized JUnit tests.

With the introduction of Junit 4, a lot has changed for testing Java software with Junit. One of the more esoteric additions are parametrized tests. It allows a developer to run a great deal of test which differ only in a set of parameters. Without further ado I will show you a parametrized test.

@RunWith(Parameterized.class)
public class FactorizationTest
{
    private int number;

    private List expectedResult;

    public FactorizationTest(int number, Integer[] result)
    {
        this.number = number;
        this.expectedResult = Arrays.asList(result);
    }

    @Test
    public void factorize()
    {
        assertEquals(expectedResult, Factorization.factor(number));
    }

    @Parameters
    public static Collection<Object[]> data()  
    {   
        List<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { 2, new Integer[] { 2 } });
        data.add(new Object[] { 8, new Integer[] { 2, 2, 2 } });
        data.add(new Object[] { 9, new Integer[] { 3, 3 } });
        data.add(new Object[] { 72, new Integer[] { 2, 2, 2, 3, 3 } });   
        return data;
    }
} 

Lets focus on line 17 of the method annotated with @Test. This method asserts that the expectedResult is returned by the static method Factorization.factor(int) which is called with parameter number. Both expectedResult and number are private fields of the class FactorizationTest. The fields are assigned in the constructor.

By annotating the class with the @RunWith(Parameterized.class) we are telling Junit to run this class with the Parameterized Runner. By implementing a Runner you can specify how to run the tests.

For the Parameterized this means the following. (The following section is paraphrased. See https://github.com/KentBeck/junit for the details.)

  1. Get an Collection of Object-arrays.
  2. Repeat for every Object-array in the collection:
    1. Construct an instance of FactorizationTest passing as parameters the various elements in the Object-array.
    2. Run all methods annotated with @Test.

The collection mentioned in step 1 is obtained by calling a method annotated with @Parameters. So in this example the following facts will be asserted.

numberfactors
22
82, 2, 2
93, 3
722, 2, 2, 3, 3

In this blog post I made clear how to use parameterized test in the Junit test framework.

Saturday, August 7, 2010

Java Puzzler: 1 July 1937

In this blog post I will discuss the idiosyncrasies of Java and the date of 1 July 1937 in the Netherlands. I encountered this as a bug at work.

Look at the following code. Note that my timezone is set to Europe/Amsterdam.

Calendar calendar = Calendar.getInstance();
  calendar.clear();
  calendar.set(1937, 5, 30, 23, 59, 59);
  System.out.println(calendar.getTime());

  calendar.add(Calendar.SECOND, 1);
  System.out.println(calendar.getTime());

I will tell you the output of line 4. It is Wed Jun 30 23:59:59 CEST 1937. What would you expect to be the output of line 7?
If somebody would ask me this question, I would be very suspicious. Why ask this question if the answer should obviously be Thu Jul 01 00:00:00 CEST 1937? What is going on here? But for me, without resorting to psychology, there is no other answer thinkable then the obvious.

As it turns out the answer on my machine consistently is: Thu Jul 01 00:00:28 CEST 1937.

The crucial piece of information is that the timezone is set to Europe/Amsterdam. With the timezone set to something else e.g. Europe/London, the output is the expected Thu Jul 01 00:00:00 BST 1937. So what is going on here?

As it turns out, on 1 July 1937 the dutch government decided to changed meridians for timekeeping. Apparently in 1908 a the government introduced a national means to keep time. The time in the Netherlands was determined by the time in Amsterdam. At first the Westertoren was picked as defining meridian (4° 53' 01.95" east longitude) resulting in a time difference of 19 minutes and 32 seconds with GMT.
On the first of July 1937 the 5° meridian was used to tell time to give an even time difference of 20 minutes with GMT. But this produced a 28 seconds skip in time keeping. So the first 28 seconds of 1 July 1937 do not exist in the Netherlands. This is the cause of the peculiar behavior of the above code.

reference (in dutch).

Saturday, July 24, 2010

Introduction to Software Development - Part 2

In this blog I will outline the second instalment of the introduction to software development I had with a friend of mine.

In a previous post I told the story of introducing software development to a friend. In this second run, we took on a little project to hone our developing skills.

We looked into Mancala. It is a game in which stones get sown around the board. The exercise was meant to develop a feel for architecture.

We had a lot of discussion about responsibilities. Which object should be responsible for a certain task? I think that the question of responsibility is a very good to get your bearing while developing an application.

In the subsequent meeting we will finish this little project.

Saturday, June 26, 2010

Counting Graphic Sequences

In this post I give the the number of graphic sequences of length 0 through 6.

The numbers were counted by iterating over all sequences using a custom made graphic sequence iterator.

length01234567
#11241131102342

Friday, June 25, 2010

Iterating Monotonic Decreasing Sequences

In this post I will show an algorithm to iterate over all monotonic decreasing sequences of non-negative integers of length at most \(m\) and height \(n\).

In a previous post I counted the number of monotonic decreasing sequences of length at most \(m\) and height \(n\). In order to study these objects it is nice If you can generate them all on a computer.

Furthermore, it would be nice to "visit" them one at a time. This cuts down on memory consumption, because then only one sequence has to be in memory at any time. In this blog post I will outline an algorithm to generate all the monotonic decreasing sequences of non-negative integers of length at most \(m\) and height \(n\) in lexicographical order.

Wednesday, June 2, 2010

Introduction to Software Development

In this blog I will outline how I introduced a friend to the art and craft of software development.

A friend of mine got interested in software development, but was not quit sure how to start. Because I have a strong opinion what constitutes "good" software development skills, I offered to guide him in his explorations in software development. This blog summarizes the first day of guidance.

In my opinion a software developer is not tied down to a single language. But an aspiring developer has to start somewhere. The language choice was made on two grounds: my own familiarity with languages and it's popularity in the field. We settled for Java.

After downloading the appropriate software development kit and setting up the PATH variable we could really start. I created the conical "Hello World!"-example using only a rudimentary text editor and the command line. We build upon the example by introducing the following concepts

  • Introduction of a package
  • Separation of source- and class-files
  • Introduction of the classpath
  • Objects

After this bare-boned example we set out to install an integrated development environment. I loaded the die in favor of Eclipse. After downloading and installing Eclipse I challenged my friend to reproduce the command line example. By emphasizing steps which are easer with the help of the IDE, my friend quickly reproduced the afore mentioned example. The following step was the introduction of test driven development. I showed my friend how a test can be used to guide the development of a new feature. Afterwards I explained him the virtues of test with respect to refactoring. The example was extended by writing test and constantly refactoring, thereby introducing the following concepts.

  • Inheritance
  • Method overloading
  • Interfaces
  • Abstract classes

The next step was to introduce version control. My friend could easily motivate the need for some form of version control. In the end we settled for subversion as our version control system. We downloaded a subversion client and extended the PATH variable. I showed him how the command line can be used to version a file, but we quickly installed a Subclipse. Along the way we created a google code project which now hosts are first steps. Guided by tests and committing our progress we enhanced the example with

  • Commit often, Commit Early
  • Command line arguments
  • Alternate output streams
  • Mocking

In the end I showed my friend coding katas. The main goal was to introduce a means to hone his programming skills without my presence. The secondary goal was the introduction of maven as build to. We agreed to do an other session. As a homework assignment my friend would do a kata a day, or more if he likes to. I pointed out "Head First Java" as a good book to learn Java.

This wraps up the summary of the software introduction I gave to a friend.

Tuesday, May 11, 2010

Pitfalls of Reflection

In this post I will discuss a pitfall of the use of reflection in Java. Specifically how reflection can obscure and even change the semantics of a piece of code.

What is wrong with the following example of JavaBean naming convention?

public Boolean isCorrect() {
    /* implementation not shown. */
}

Did you spot the capital B on the Boolean return type? According to the JavaBean naming convention the property does not fall under the special rules for booleans and should be named accordingly.

public Boolean getCorrect() {
    /* implementation not shown. */
}

Although there is a sleight syntactic difference, the apparent semantic difference is non-existent. According to William Shakespeare:

A rose by any other name would smell as sweet

Enter reflection. By using reflection it is possible to perform hugely different behaviour depending on the name of a method. The following whimsical example is a clear demonstration of this fact.

Class aClass = ReflectedClass.class;
Method method;
try
{
    method = aClass.getDeclaredMethod("isCorrect");
    protect(Planet.EARTH);
}
catch (NoSuchMethodException e)
{
    destroy(Planet.EARTH);
}

So one of the pitfalls of reflection is the hidden semantics associated with code. Stated in other words: the influence of code can not be inferred by the syntactic definition of that code.

Saturday, April 10, 2010

Qwickie: a usefull eclipse plugin for Wicket Development

In this post I will introduce Qwickie, a usefull eclipse plugin for Wicket Development.

In my daily work I develop software applications. As a web framework we use Wicket, a component based framework with a clear separation of the presentation and the logic.

The connection you between presentation and logic is made via "wicket:id"'s. (See the wicket examples page how this is done.) I found myself executing the following behavioural pattern or it's inverse a lot.

  1. Seek a wicket:id in a webpage
  2. Find corresponding wicket:id in the code

Recently I came across a nice little eclipse plugin which speeds up this pattern. It is named Qwickie, and it facilitates the following use cases:

  • Navigate from java code elements to the corresponding html element via wicket:id
  • Show the corresponding html fragment from the java code element

Both actions are performed by clicking the wicket:id while holding down the ctrl button. This shaves off time following the association between presentation and logic.