This got me interested in how a program like Shazam works… And more importantly, how hard is it to program something similar in Java?

About Shazam

Shazam is an application which you can use to analyse/match music. When you install it on your phone, and hold the microphone to some music for about 20 to 30 seconds, it will tell you which song it is.

When I first used it it gave me a magical feeling. “How did it do that!?”. And even today, after using it a lot, it still has a bit of magical feel to it.
Wouldn’t it be great if we can program something of our own that gives that same feeling? That was my goal for the past weekend.

Listen up..!

First things first, get the music sample to analyse we first need to listen to the microphone in our Java application…! This is something I hadn’t done yet in Java, so I had no idea how hard this was going to be.

Now we can read the data from the TargetDataLine just like a normal InputStream:

// In another thread I start:
OutputStreamout=newByteArrayOutputStream();running=true;try{while(running){intcount=line.read(buffer,0,buffer.length);if(count>0){out.write(buffer,0,count);}}out.close();}catch(IOExceptione){System.err.println("I/O problems: "+e);System.exit(-1);}

Using this method it is easy to open the microphone and record all the sounds! The AudioFormat I’m currently using is:

So, now we have the recorded data in a ByteArrayOutputStream, great! Step 1 complete.

Microphone data

The next challenge is analyzing the data, when I outputted the data I received in my byte array I got a long list of numbers, like this:

0
0
1
2
4
7
6
3
-1
-2
-4
-2
-5
-7
-8
(etc)

Erhm… yes? This is sound?

To see if the data could be visualized I took the output and placed it in Open Office to generate a line graph:

Ah yes! This kind of looks like ‘sound’. It looks like what you see when using for example Windows Sound Recorder.

This data is actually known as time domain. But these numbers are currently basically useless to us… if you read the above article on how Shazam works you’ll read that they use a spectrum analysis instead of direct time domain data.
So the next big question is: How do we transform the current data into a spectrum analysis?

Discrete Fourier transform

To turn our data into usable data we need to apply the so called Discrete Fourier Transformation. This turns the data from time domain into frequency domain.
There is just one problem, if you transform the data into the frequency domain you loose every bit of information regarding time. So you’ll know what the magnitude of all the frequencies are, but you have no idea when they appear.

To solve this we need a sliding window. We take chunks of data (in my case 4096 bytes of data) and transform just this bit of information. Then we know the magnitude of all frequencies that occur during just these 4096 bytes.

Implementing this

Instead of worrying about the Fourier Transformation I googled a bit and found code for the so called FFT (Fast Fourier Transformation). I’m calling this code with the chunks:

byteaudio[]=out.toByteArray();finalinttotalSize=audio.length;intamountPossible=totalSize/Harvester.CHUNK_SIZE;//When turning into frequency domain we'll need complex numbers:
Complex[][]results=newComplex[amountPossible][];//For all the chunks:
for(inttimes=0;times<amountPossible;times++){Complex[]complex=newComplex[Harvester.CHUNK_SIZE];for(inti=0;i<Harvester.CHUNK_SIZE;i++){//Put the time domain data into a complex number with imaginary part as 0:
complex[i]=newComplex(audio[(times*Harvester.CHUNK_SIZE)+i],0);}//Perform FFT analysis on the chunk:
results[times]=FFT.fft(complex);}//Done!

Now we have a double array containing all chunks as Complex[]. This array contains data about all frequencies. To visualize this data I decided to implement a full spectrum analyzer (just to make sure I got the math right).
To show the data I hacked this together:

for(inti=0;i<results.length;i++){intfreq=1;for(intline=1;line<size;line++){// To get the magnitude of the sound at a given frequency slice
// get the abs() from the complex number.
// In this case I use Math.log to get a more managable number (used for color)
doublemagnitude=Math.log(results[i][freq].abs()+1);// The more blue in the color the more intensity for a given frequency point:
g2d.setColor(newColor(0,(int)magnitude*10,(int)magnitude*20));// Fill:
g2d.fillRect(i*blockSizeX,(size-line)*blockSizeY,blockSizeX,blockSizeY);// I used a improviced logarithmic scale and normal scale:
if(logModeEnabled&&(Math.log10(line)*Math.log10(line))>1){freq+=(int)(Math.log10(line)*Math.log10(line));}else{freq++;}}}

Introducing, Aphex Twin

This seems a bit of OT (off-topic), but I’d like to tell you about a electronic musician called Aphex Twin (Richard David James). He makes crazy electronic music… but some songs have an interesting feature. His biggest hit for example, Windowlicker has a spectrogram image in it.
If you look at the song as spectral image it shows a nice spiral. Another song, called ‘Mathematical Equation’ shows the face of Twin! More information can be found here: Bastwood - Aphex Twin’s face.

When running this song against my spectral analyzer I get the following result:

Not perfect, but it seems to be Twin’s face!

Determining the key music points

The next step in Shazam’s algorithm is to determine some key points in the song, save those points as a hash and then try to match on them against their database of over 8 million songs. This is done for speed, the lookup of a hash is O(1) speed. That explains a lot of the awesome performance of Shazam!

Because I wanted to have everything working in one weekend (this is my maximum attention span sadly enough, then I need a new project to work on) I kept my algorithm as simple as possible. And to my surprise it worked.

For each line the in spectrum analysis I take the points with the highest magnitude from certain ranges. In my case: 40-80, 80-120, 120-180, 180-300.

//For every line of data:
for(intfreq=LOWER_LIMIT;freq<UPPER_LIMIT-1;freq++){//Get the magnitude:
doublemag=Math.log(results[freq].abs()+1);//Find out which range we are in:
intindex=getIndex(freq);//Save the highest magnitude and corresponding frequency:
if(mag>highscores[index]){highscores[index]=mag;recordPoints[index]=freq;}}//Write the points to a file:
for(inti=0;i<AMOUNT_OF_POINTS;i++){fw.append(recordPoints[i]+"\t");}fw.append("\n");// ... snip ...
publicstaticfinalint[]RANGE=newint[]{40,80,120,180,UPPER_LIMIT+1};//Find out in which range
publicstaticintgetIndex(intfreq){inti=0;while(RANGE[i]<freq)i++;returni;}}

Indexing my own music

With this algorithm in place I decided to index all my 3000 songs. Instead of using the microphone you can just open mp3 files, convert them to the correct format, and read them the same way we did with the microphone, using an AudioInputStream. Converting stereo music into mono-channel audio was a bit trickier then I hoped. Examples can be found online (requires a bit too much code to paste here) have to change the sampling a bit.

Matching!

The most important part of the program is the matching process. Reading Shazams paper they use hashing to get matches and the decide which song was the best match.

Instead of using difficult point-groupings in time I decided to use a line of our data (for example “33, 47, 94, 137”) as one hash: 1370944733
(in my tests using 3 or 4 points works best, but tweaking is difficult, I need to re-index my mp3 every time!)

Now we already have everything in place to do a lookup. First I read all the songs and generate hashes for each point of data. This is put into the hash-database.
The second step is reading the data of the song we need to match. These hashes are retrieved and we look at the matching datapoints.

There is just one problem, for each hash there are some hits, but how do we determine which song is the correct song..? Looking at the amount of matches? No, this doesn’t work…
The most important thing is timing. We must overlap the timing…! But how can we do this if we don’t know where we are in the song? After all, we could just as easily have recorded the final chords of the song.

By looking at the data I discovered something interesting, because we have the following data:

- A hash of the recording
- A matching hash of the possible match
- A song ID of the possible match
- The current time in our own recording
- The time of the hash in the possible match

Now we can substract the current time in our recording (for example, line 34) with the time of the hash-match (for example, line 1352). This difference is stored together with the song ID. Because this offset, this difference, tells us where we possibly could be in the song.
When we have gone through all the hashes from our recording we are left with a lot of song id’s and offsets. The cool thing is, if you have a lot of hashes with matching offsets, you’ve found your song.

The results

For example, when listening to The Kooks - Match Box for just 20 seconds, this is the output of my program:

Here are (in my opinion) five of the most important ‘rules’ in software development.

Changes happen

The reason why waterfall doesn’t work and agile works a lot better. Changes happen. People will always change their mind, over time technology changes and situations change. So during software development you will have to be flexible with the requirements.

Create software that the client wants, not what he says he wants.

What the clients tells you he wants might not (entirely) be what he/she actually wants or the organisation needs. It is vital to ask questions and release early. When you have something visible, let the client judge it.
Some people say there is one major drawback of showing designs and the application early on, the client probably gets new ideas and wants to change the design. But that actually is a good thing, you still have much time left to plan these changes! If you do a waterfall-method and release on delivery date.. the client still wants his/her changes (!).

Always write down decisions.

During a project, especially during the startup, there are a lot of choices to be made. Is it going to be a web application, or standalone? What frameworks are we going to use?
All these decisions are made with arguments, pro’s and con’s, write those down! A project-wiki would be a perfect place. If some members leave the team and new members join the team this information is vital. When the new members join the team their first reaction will be “Why are they doing it this way and not …?”. Reading the argumentation will help them understand the situation and get them up to speed. Also, during projects there are always moments when you reflect on choices made in the past: “Why did we do … wouldn’t we have done better if we did/used …”. You can now always review the past arguments to see if the current situation has changed so much that a reconsideration would be in order or not.

The team owns the code.

If you write a piece of code, it is not your code. The code belongs to the collective, the team. If somebody changes your code, embrace it, it was probably needed. If you see an ugly piece of code you didn’t write, you are also responsible, refactor it.

Commit driven development.

Test driven development is a great idea. First write a unit-test, check to see if it fails, now write your code until the test succeeds. This way you know two important things, the final code is easy to test (it was written with testing in mind) and the code does what the test expects. But there is one major drawback, most people (not all) simply can’t work this way. For some people it works great, but some developers want to write their tests afterwards. And that is ok, there is just one important rule: Never check your code in (the trunk) if it isn’t tested and doesn’t have proper documentation (e.g. JavaDoc). So: It is no problem if you write code and then tests, or tests then the code, as long as you write them before commiting to your SCM repository.

There are situations when you need to write a lot of new code, in that case you still want to be able to check your code in, even if you aren’t done yet. For these situations you create a feature-branch. On this branch you develop all the new funtionality and once it is done, documented and tested, merge it with the trunk.

The last couple of weeks I have been playing around with compression/decompression algorithms. This is a field that has always intrigued me. It gives me a magical feeling, like a magician you wave some algorithm around and suddenly the files shrink and bytes dissapear. With the same motion you can undo all your actions and re-generate the original files from thin air!

Arithmetic Coding

Arithmetic coding is a different method to encode bytes. On itself it doesn’t compress, but it is the backbone of a whole family of compression algorithms. To explain how it works we need some example text we want to compress: “ABACB”

First we assign a probability to each symbol:

A: 45%

B: 40%

C: 15%

Lets change these probabilities into ranges from 0.0 to 1.0:

A: 0.00 to 0.45

B: 0.45 to 0.85

C: 0.85 to 1.00

Now we start reading our input (ABACB). The first character we find is ‘A’. First we do a lookup in the table, what range does ‘A’ have: 0.00 to 0.45. Lets remember these values as ‘low’ and ‘high’.

Time to encode the second character ‘B’. The first thing we need to do is reset our ranges to be between low and high:

A: 0.0000 to 0.2025

B: 0.2025 to 0.3805

C: 0.3805 to 0.4500

We want to encode ‘B’, so we’ll end up with low=0.2025 and high=0.3805. Time to update the table again:

A: 0.2025 to 0.2826

B: 0.2826 to 0.3538

C: 0.3538 to 0.3805

Encode ‘A’, we get low=0.2025 and high=0.2826. And adjust the table again:

A: 0.202500 to 0.238545

B: 0.238545 to 0.270585

C: 0.270585 to 0.282600

Encode ‘C’, we get low=0.270585 and high=0.282600. Adjust the table one last time:

A: 0.27058500 to 0.27599175

B: 0.27599175 to 0.28079775

C: 0.28079775 to 0.28260000

So, lets encode the final symbol ‘B’ and stop right here. Now we save/output a value betwee low (0.27599175) and high (0.28079775) which takes the least amount of bytes, for example 0.28!

Now I we want to decode our message “0.28” we start by building the ranges again, these are the same as the first table above. Now we look at which range our 0.28 fall in. The result is ‘A’ (between 0.0 and 0.45). So we output this symbol. Next we have to update the table, because we outputted ‘A’ we know our encoder encoded ‘A’, so we can follow the same steps as the encoder did and update the ranges in the same way, so we’ll end up with the second table (with values between 0.0 and 0.45). If we look at 0.28 it now falls into range ‘B’, so we output ‘B’ and adjust again.

As you can see this number “0.28” describes our whole message “ABACB”! So we encoded a whole message in one small number. There are a lot of improvements possible to implement this algorithm efficiently, for example look at range encoding. Another website that helped me a lot is this basic arithmetic coding by Arturo Campos.

Prediction

The previous example works great, but there is a problem… if we assign equal probabilities to each possible symbol (each byte) we won’t compress anything! The example above works because I took bigger probabilities for A and B then for C… So for it to work we need to guess the correct probabilities, and the better we do this, the smaller our file gets! Luckely there are a couple of methods to assign/guess these probabilities.

Read and save table

One thing you can do is to first read the whole file and save the amount you see each character. Then you can scale these amounts into probabilities between 0.0 and 1.0 and save these probabilities to a file. Next we can use these probabilities to encode (and decode) our message! This will take quite a bit of overhead because you have to save the table..

Runtime adjustment

Another thing we can do is to just start with equal probabilities for each symbol and adjust the probabilities during the encoding. If we use the same method in encoding and decoding our probability table will remain the same.

Prediction by Partial Matching (PPM)

So, we can adjust the probabilities at runtime and for example count all the symbols we have seen. But why stop there? For example in a piece of English text, the letter ‘E’ will probably have the highest count/probabilty. But if we encouter the symbols: “COMPRESSI” we know the next character will likely be an “O”, not an “E”! So what if we can enlarge our context? This is what PPM does, looking at the bigger picture. Not only count single symbols, but also combinations. The longer the combinations the more specific our predictions get (but also more memory is needed).

Context Mixing (CM)

With PPM you have one model which predicts the probability of the next symbol by looking at its past statistics. But why stop there? With Context Mixing (CM) you can have multiple models predicting the next symbol work together. When you do this right you and predict the next symbol even better and thus get better compression ratios! This is how the best current compression algorithms work.

Other methods

This is just one family of compression algorithms, there are a lot more which I won’t describe here (yet?). Instead of processing/guessing the next symbol you could also replace long series of symbols with shorter unique symbols. This is known as dictionary coding, an entire other family of compressors (including LZ, zip, gz).

Its a problem I encouter in most JEE projects I’ve worked on so far. Handling null-values. But why is this a problem? And what strategies can we follow to reduce the problem? That is what I’m trying to find out in this post.

Lets start with a piece of business logic, in a world where we don’t have null-values:

Wow, that is not a pretty sight, not at all! What can we do about it and how did it happen?

Inversion of logic

The first strategy we can follow is based on inversion of logic which I’ve blogged about before. The idea is that we exit early, this will improve the readability of our method. Lets see that happens to our method is we follow this pattern:

This is somewhat better, a bit shorter, but we still have all the ‘!= null’ and ‘== null’ checks we don’t want.

Code by contract

The best way to get rid of null-checks is to get rid of nulls in your applicaties. Just don’t return a null in all of the methods…! This sounds very easy and straight forward, but it is a bit harder then it sounds because it has become such a habbit.

The good thing is that current IDE’s are implementing the @NotNull and @Nullable annotations. With these annotations you can tell other programmers, your IDE and static code analysis tools what your idea was when creating a method:

@NullablepublicPersongetPerson(Longid){returnsomething.retrievePerson(id);}publicvoidprintPersonName(Longid){Personperson=getPerson(id);System.out.println(person.getName());//Causes warning: getPerson is Nullable, thus this is a possible NPE!
}

It also helps you to clearly state your assumed preconditions:

publicvoidprintPersonName(@NotNullPersonperson){System.out.println(person.getName());//Very good, we know we won't get a NPE here!
}publicvoidexecuteThis(){Personperson=null;printPersonName(person);//Causes warning: person might be null, thus can cause a NPE!
//Code analysis tools and/or IDE will warn you about this.
}

Using this method you have some more certainties. But it isn’t a silver-bullet on its own. We have to stop and think, where do the null-values come from?

Actually, when you stop returning null (which is entirely up to you and your team) there are still situations which are ‘unchecked’. Namely external API’s, frameworks, the ORM-mapper you are using. So everywhere where you execute methods that you haven’t written, you still have to do manual checks. But make sure you do this right away. Then further on in the code, you don’t have to check anything because of your @NotNull-contracts.
If you do this to the Person object above, and all its fields, you will end up with the beautiful clean code of the first example. No checks, its just always filled by contract. The only thing you want to add is information about the parameters:

In my experience this works very well, I’ve done this a couple of times, even before the @NotNull and @Nullable existed. Before this we would just add the information in our Javadoc. But with the IDE checking for it this has become a lot easier to use.

Null object pattern

A whole different approach then coding-by-contract is the use of a null-object. The idea behind this pattern is that you don’t return null, but instead you return a real object. In our example we would do the following:

The huge advantage is that you can always safely call “person.getName()” and “person.getAccounts()” because even if you have a NullPerson the object still exists. This Null-Object is obviously usually a singleton.

Now you can return much more information then just a meaningless “null”!

There is just one problem with this pattern. It also doesn’t just solve your problems. Why do we want to calculate the total balance of a NullPerson? The moment you retrieve a person and it is an instance of NullPerson, catch it and handle the situation appropiatly, don’t just continue.

Safe null operator

For a time there was speculation that the Safe-null-operator would make its way into Java 7 through Project Coin. If you’ve programmed in Groovy you might have seen it before:

For the Queue ICPC programming game Capture I ran into a geometrical problem.
While programming my little robot I wanted to have an algorithm calculate this for me:

I have a field with 122 points

I have a circle of fixed size

How do I calculate where to put the circle so it encapsulates the most points?

This is what I came up with, three algorithms:

Algorithm #1: Centerpoint

The first algorithm was created as a test. It doesn’t find the perfect solution, but gives a decent solution.
First I loop over all the points, and I check if there are points located at CIRCLE_RADIUS length from our point. This returns a score. The best point has a lot of other points nearby.

This algorithm is very quick, but it has a huge disadvantage, the circle will always have one of our points as center.

It will never yield the perfect solution… In the following picture this algorithm produces the green circle:

Algorithm #2: Heatmap

The next idea I got was based on a heatmap. It is very computer heavy, but it will generate the best solution.

The pixel with the best score is used in most circles. Thus, this would need to be the center of our circle!

In the image above you can see the resulting heatmap, and the cyan circle is placed on the best possible pixel.

(In most cases, there are more then one ‘best pixels’, which one you choose doesn’t matter)

Algorithm #3: Bron-Kerbosch-myself

The heatmap algorithm, mentioned above, takes a LOT of processing time and is far from the most efficient algorithm. For the Queue ICPC contest there is a time limit for each calculation, and I need it to speed up!

So I started to wonder:

- What do all the points in the perfect circle have in common?

Well, they all have a maximum distance to each other of CIRCLE_RADIUS * 2.

So I started to play with graph algorithms.

The lines you see in the image above are all the points that can be connected with a maximum length of CIRCLE_RADIUS * 2. All the lines show points that could possibly be in the same circle together.
Then I googled a bit and found the term ‘clique’. A clique is a group of points that all point to each other, just what we want with the graph shown in the picture!

When I searched a little further I came across the Bron-Kerbosch algorithm. It finds the perfect maximum clique for a given undirected graph! Again, just what we want!

But I ran into a little problem, I’d made a false assumption… If you have a triangle of three points, with all legs size N, and then draw a circle from the center… none of the points fall into the circle.

Now I tried two ways to solve this, the first one is to use a smaller distance in the graph. If you only select points that are located (cosine(30) * CIRCLE_RADIUS * 2) every point will eventually fall into our circle. But this could eliminate the perfect circle obviously if two points in the perfect solution are further apart then (cosine(30) * CIRCLE_RADIUS * 2).

Then I desected the Bron-Kerbosch algorithm, and decided to change it a bit. This is what I ended up with:

This returns all the maximal cliques that fall into our circle, and we are always sure they fall into our circle..! I think this will always generate the perfect solution, just as the heat map. In this the above picture, this algorithm produces the red circle.

It already is light years faster then the heat map algorithm, but I still need a bit more speed. I’m still struggling to improve my implementation, like trying to use a pivot as bronKerbosch2 (see wikipedia again) does.

Algorithm #4: ???

For some reason I still fail to believe I’m the first person in the world to tackle this problem. But I haven’t been able to find an algorithm for this. Some people recommended using a sweeping algorithm but I don’t understand how this is used to find the circle’s location. Others pointed me to Voronoi maps…

So if you have any suggestions, or know the algorithm I’m looking for, please add a comment :-)

Recently I placed a comment on this interesting blog from Uncle Bob Martin (Robert C. Martin). It contains a brief description on how I teach people how to use the Spring Framework.

Now, by popular demand (one person requested it over Twitter), I’ll guide you through the method and examples I use in this blogpost. It explains why people should use frameworks like Spring and/or Google Guice, and how.

The implementation of this DAO isn’t really interesting, lets just pretent it goes to the database:

packagenl.redcode.examples.milkman;publicclassMilkDAODatabaseImplimplementsMilkDAO{publicvoidsaveOrder(Stringcustomer,IntegeramountOfBottles){//Puts order in database
}}

And finally we have our service implementation:

packagenl.redcode.examples.milkman;publicclassMilkRequestServiceImplimplementsMilkRequestService{privateMilkDAOmilkDAO;/**
* Create a new service:
*/publicMilkRequestServiceImpl(){milkDAO=newMilkDAODatabaseImpl(//With SQLConnection or something
);}/**
* Place a new order for milk.
*/publicvoidprocessOrder(Stringcustomer,IntegeramountOfBottles){//Log the order:
System.out.println("LOG: Customer "+customer+" wants "+amountOfBottles+" bottle"+((amountOfBottles>1)?"s":""));//Save the order:
milkDAO.saveOrder(customer,amountOfBottles);}}

Lets pretent that we are good obeying programmers, although we didn’t write our unit test up front, we are going to do it right away.

So… we want to test the service, how are we going to do this? Well, lets just create the service, call it, and then check if it does what we want it to do!

packagenl.redcode.examples.milkman;publicclassMilkRequestServiceTest{MilkRequestServicemilkRequestService=newMilkRequestServiceImpl();@Test/**
* Test our milk request service.
* Pre:
* - We have a customer that wants to order 5 bottles of milk
* Post:
* - The milk DAO got a request to save 5 bottles of milk
*/publicvoidtestProcessOrder(){finalStringcustomer="testUser";finalIntegeramountOfBottles=5;milkRequestService.processOrder(customer,amountOfBottles);//Eeehh.... how do we check the call to the DAO?
//HELP!!
}}

We run into a problem rather quickly. Now this code makes a connection to the database and it might or might not save our order. But how do we check this? We could go to the database and check…

NO! Never go to the database in a unit test. We only want to test a single unit of work, and the database ain’t one of them.

We need to refactor our code…!

The Factory

One possible solution to this problem is using a factory method. A factory creates objects so you don’t have to. Its best shown using an example:

The method get(class, object) will return an implementation for a given Class. It uses a Map to get the mapping. The map is created during the static initialization (yuk!) and contains the default mapping, but we can also provide our own mapping using replaceMapping(class, object).

Now how do we use it? Lets see our new MilkRequestServiceImpl:

packagenl.redcode.examples.milkman;publicclassMilkRequestServiceImplimplementsMilkRequestService{/**
* Place a new order for milk.
*/publicvoidprocessOrder(Stringcustomer,IntegeramountOfBottles){//Log the order:
System.out.println("LOG: Customer "+customer+" wants "+amountOfBottles+" bottle"+((amountOfBottles>1)?"s":""));//Save the order:
MilkFactory.get(MilkDAO.class).saveOrder(customer,amountOfBottles);}}

As you can see we no longer need the constructor, we get the required DAO from the factory when we need it.

Now we can test it using the replaceMapping method:

packagenl.redcode.examples.milkman;publicclassMilkRequestServiceTest{MilkRequestServicemilkRequestService=newMilkRequestServiceImpl();//@Test
/**
* Test our milk request service.
* Pre:
* - We have a customer that wants to order 5 bottles of milk
* Post:
* - The milk DAO got a request to save 5 bottles of milk
*/publicvoidtestProcessOrder(){finalStringcustomer="testUser";finalIntegeramountOfBottles=5;//Better use a mock here, for example using Mockito or EasyMock.
MilkFactory.replaceMapping(MilkDAO.class,newMilkDAO(){publicvoidsaveOrder(Stringcustomer,IntegeramountOfBottles){//Check if the customer = testUser
//Check if the amountOfBottles = 5;
}});MilkFactory.get(MilkRequestService.class).processOrder(customer,amountOfBottles);}}

As the comment says, you are probably much better of here using a mocking framework like EasyMock or Mockito. But the point is, we can test our class now without going to the database! We got our control back.

Dependency Injection

Instead of writing a factory, there is a better way to do this. It is the Hollywood principle “Don’t call us, we’ll call you”.

All the dependencies of the objects are injected into them instead of created (initial example) or retrieved (factory example). So our service will look like this:

packagenl.redcode.examples.milkman;publicclassMilkRequestServiceImplimplementsMilkRequestService{privateMilkDAOmilkDao;/**
* The milkDao is given to us by our creator.
*
* @param milkDao
*/publicMilkRequestServiceImpl(MilkDAOmilkDao){this.milkDao=milkDao;}/**
* Place a new order for milk.
*/publicvoidprocessOrder(Stringcustomer,IntegeramountOfBottles){//Log the order:
System.out.println("LOG: Customer "+customer+" wants "+amountOfBottles+" bottle"+((amountOfBottles>1)?"s":""));//We just use the milkDao we got:
milkDao.saveOrder(customer,amountOfBottles);}}

Now lets take a look at our test-code, it now looks like this:

publicvoidtestProcessOrder(){finalStringcustomer="testUser";finalIntegeramountOfBottles=5;//Better use a mock here, for example using Mockito or EasyMock.
MilkDAOtestMilkDao=newMilkDAO(){publicvoidsaveOrder(Stringcustomer,IntegeramountOfBottles){//Check if the customer = testUser
//Check if the amountOfBottles = 5;
}};MilkRequestServicemilkRequestService=newMilkRequestServiceImpl(testMilkDao);milkRequestService.processOrder(customer,amountOfBottles);}

We now have full control over the wiring. First we create our own little testMilkDao (use a mock here!) and we place it into our service. That’s all. Instead of the hidden creation in the service itself or in the factory we are in full control.

But if you want to use this application you’ll need “something else” to create all the objects and do the actual wiring. Lets create our own Spring or Google Guice..!!

Why does my car do this to me? It bugs me everyday. When I drive with the snow outside I have to use my windscreen washer quite a lot. When I pull the little lever behind my steering wheel it spurts a jet of antifreeze/washer fluid onto my screen and it starts to wipe for about 10 times. Then it stops… my window is clean again!

But after about 15 seconds it does one final sweep… and this last sweep always leaves ugly marks!

Why do cars do this!!!? First it cleans my window perfectly, and then spoils it!

Update:
A collegue adviced me this: If the car has just finished wiping, quickly switch on the manual and stop it. This will still cause one extra wipe, but it comes right after the others. This produces a slightly better result.

I tried this two times on my car (a Fiat Bravo) and it worked one time, the other time it still did the final whipe after around 10 seconds.

MD5 quines

Sometimes I let my mind wonder and I get crazy questions. Today was a good example, I encountered a MD5 hash and I started to wonder, would there be a hash which would (when hashed again) be the same?

Thus: MD5(x) = x

This would be a kind of MD5 quine, when fed into the algorithm you get the original value back. This is actually called an MD5 fixed point.

Information I’ve found

So I started investigating, soon I discovered this website about collisions. Its well known that all hashing algorithms must have collisions, you can’t always produce a unique hash for input larger then the output of course.

The output of the MD5 sum is 128 bit (16 byte) long, so the input should also have the same length. But the MD5 algorithm is defined to have 512 bits as input. This isn’t really a problem because the algorithm will extend smaller input with padding. Lets assume the MD5 sum of any input is uniformly distributed over all possible sums, then the probability that a 128-bit string is a fixed point is 1/2^128. This isn’t a crazy assumption because all hashing-algorithms are designed to distribute the output as uniformly as possible to avoid collisions.

So, the probability that no 128-bit string is a real fixed point is (1 - 1/2^128)^(2^128). The probability that there IS a fixed point is 1 - (1 - 1/2^128)^(2^128).

Since the limit as N goes to infinity of (1 - 1/N)^N is 1/e, and 2^128 is most certainly a very large number, this probability is almost exactly 1 - 1/e = 63.21%.

But, of course, there is no randomness involved here - there either is a fixed point or there isn’t. But, we can be 63.21% confident that there is a fixed point. (Also, notice that this number does not depend on the size of the keyspace - if MD5 sums were 32 bits or 1024 bits, the answer would be the same).

Looking for the fixed point

I’ve just implemented a small program to look for these hashes, even though I know it will take millions of years to check all the numbers. But you never know, I might get lucky ;-)

The first algorithm I created took a single random String as input and kept applying the algorithm to the output. Eventually it will:

Go into a loop

Find a fixed point (which is a loop of size 1)

The weird thing is, if it ends up in a loop of size 1… I’ve found two things. Not only a md5 fixed point, which creates itself after applying the algorithm. But also an input-value that produces this md5 as output, a collision!

Graph

Another interesting thing would be a complete graph of all md5 answers. Which loops can we find, which md5 has most collisions etc. But this would take eternity to calculate, even using all the machines in the world.

Open questions

Are there loops? (It is possible there aren’t any loops at all…?)

Are there loops of size 1, a.k.a. fixed points?

Which/how many 128 bit combinations can’t be created with the input values?

In our current project we want to have multiple Spring Web Flow-flows in one WAR-file. But we also want the flows and pages to be inside seperate JAR files, making the application a bit more managable and modulair.

This sounds straightforward but it took quite a bit of code and time…

First I created a single WAR-project with all the basic Spring, JSF and Facelet configuration. Like any Spring Web Flow (SWF) project we have a project-servlet.xml.

The classpath*: allows SWF to search the whole classpath for flow-directories containing a flow definition.
In our case it would be: /flows/module1/module1-flow.xml

When you try to run this, and access a page we got the following exception:

Caused by: java.lang.IllegalStateException: A ContextResource is required to get relative view paths within this context; the resource was file [D:\projects\projectfromjar\module1\bin\flows\module1\page1.xhtml]
at org.springframework.faces.webflow.FlowViewHandler.resolveResourcePath(FlowViewHandler.java:110)
at org.springframework.faces.webflow.FlowViewHandler.restoreView(FlowViewHandler.java:74)
at com.sun.facelets.FaceletViewHandler.restoreView(FaceletViewHandler.java:316)
at org.springframework.faces.webflow.JsfViewFactory.getView(JsfViewFactory.java:93)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:193)
at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
... 38 more

For some reason Spring Web Flow doesn’t want to load the facelet. After browsing around Spring’s forums I came across some solutions. They didn’t do the trick, only when combining several methods I got it working for Spring Web Flow 2.0.7.

This is how I did it, we need to tell Facelets to use our custom ClassPathResourceResolver:

<!-- To load flows and pages from JARs, use this resolver --><context-param><param-name>facelets.RESOURCE_RESOLVER</param-name><param-value>nl.redcode.ClassPathResourceResolver</param-value></context-param>

This will help Facelets to translate a given path to a java.net.URL using the current classloader.
Spring Web Flow is currently giving us a FileSystemResource, and this doesn’t work because we want to load the pages with our classloader. For this we have the following wrapper:

To force Spring to use this Resource instead of FileSystemResource we use a post processor:

packagenl.redcode;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.config.BeanPostProcessor;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.GenericApplicationContext;importorg.springframework.core.io.ClassPathResource;importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;importorg.springframework.webflow.definition.registry.FlowDefinitionRegistry;publicclassFlowRegistryClassPathPostProcessorimplementsBeanPostProcessor{publicObjectpostProcessBeforeInitialization(Objectbean,StringbeanName)throwsBeansException{returnbean;}publicObjectpostProcessAfterInitialization(Objectbean,StringbeanName)throwsBeansException{if(beaninstanceofFlowDefinitionRegistry){alterRegistry((FlowDefinitionRegistry)bean);}returnbean;}protectedvoidalterRegistry(FlowDefinitionRegistryregistry){for(StringflowId:registry.getFlowDefinitionIds()){ApplicationContextctx=registry.getFlowDefinition(flowId).getApplicationContext();overrideResourceLoader((GenericApplicationContext)ctx);}}/**
* Override the ResourceLoader:
* We know our flow is always defined as "flows/module1".
* From the context we can derive the name of the flow (module1)
* So we build up the ClassPathResource base as:
* "flows/"+ ctx.getResource("")+ "/"
*
* @param ctx
*/protectedvoidoverrideResourceLoader(GenericApplicationContextctx){finalClassPathResourcecpr=newClassPathResource("flows/"+ctx.getResource("").getFilename()+"/");ctx.setResourceLoader(newResourceLoader(){publicClassLoadergetClassLoader(){returncpr.getClassLoader();}publicResourcegetResource(Stringlocation){returnnewCustomClassPathContextResource(cpr.getPath()+location,getClassLoader());}});}}

When the FlowDefinitionRegistry is created we provide it with a new ResourceLoader. When the resources are requested by Spring Web Flow we create our own CustomClassPathContextResource. This consists of our current location plus the defined location (viewId).

Its also possible to have pages in other places, you can define the views as relative paths. For example:”../../shared_pages/page2.xhtml” turns into “/shared_pages/page2.xhtml””../pages/page3.xhtml” turns into “/flows/pages/page3.xhtml”

The only problem we still have using this method is the deployment with RAD/Eclipse WTP and Facelets auto-refresh. For some reason after deploying our application locks the files in the bin-directory. Eclipse then can’t delete this directory and fails to publish. Ending in one big #fail. But a simple clean, clean, republish, clean, rebuild, restart, shout, scream, cry, rebuild and republish will solve this.

The big advantage is the fact that the flows and pages are now defined in their own JAR files, making releases and sharing classes (like shared services/shared menu’s etc) much easier.

Design patterns

Almost all programmers have heard about and used design patterns. And there are a lot of them. Famous design patterns include the Singleton, Observer, Template method. These are all patterns that focus on objects and the relationship between them.

There are more groups of patterns, for example take Dependency Injection (or Inversion of Control). This is an architectural pattern. They tell you things about the design of the whole program. And there are specific pattern groups, like concurrency patterns.

These patterns help you solve common problems in a well defined way, other programmers will recognise the patterns used and it will help produce more maintainable code.

Inversion of logic

The patterns described above all say something about classes/methods and architecture. But I think another class of design patterns exist, which have a smaller granularity. These patterns say something about the code inside a single method. A good example is Inversion of logic.

Its a basic car-rental service and is has some logic before a request is processed. To make this code more readable and maintainable we can do two things. Of course it would be better to factor out the validation-logic into another piece of code. So lets do that first:

Some programmers don’t like the validateRequest() method above because there are multiple exit points. This was more problematic in C code then in Java because in C you needed to do a bit more resource management (freeing mallocs etc), in Java I actually don’t mind having more then one exit-point in my code. In this case it makes it just a bit more readable. It would be easy to add a ‘requestIsValid’ boolean and fill that instead.

Anyway, the next step in refactoring this code is using what I call “Inversion of Logic”. The idea is that you don’t continue nesting if something is true, but instead inverse it, and bail out if something is false. The big advantage is that you’ll lose a lot of nesting, making the code more readable. I’m going to do this in two places, first in the processRequest for-loop, and second in the validateRequest method.

As you can see in the for-loop all the business logic is moved one indent back, this will make your code easier to scan for business rules. And if you look at the validateRequest method the code reads more fluent. Instead of stacking up and remembering the valid cases:

IF form is correct
AND tenant age correct
AND tenant licence is valid
THEN proceed

We now eliminate the bad cases first:

IF form is incorrect: deny rental
IF tenant’s age or licence is invalid: deny rental
ELSE proceed

I’m trying to do this everywhere I can, it realy helps the readability.

Today marks the release of Java EE 6. The reference implementation (Glassfish V3) has been released and the specifications are going into their final state very soon.

About two years ago, while I was attending the JavaOne conference, I first heard about the Servlet 3.0 ideas. As a web developer I’ve worked a lot with these Servlets so I was curious about the ideas. But what I saw wasn’t what I hoped for. On the contrary, what I saw was a huge mistake in my opinion!

So I decided to contact the guys behind this JSR, to ask for some more information and share my views. Some time passed but I never got a reply… My next move was just to write about it, first on my own blog, then on DZone (05/30/2008) and on The Server Side a half year later, december 2008.

The only ‘reply’ I got from the people of the JSR was in the days following my (re-)post on The Server Side. Glassfish has a short re-cap on what happened here.

Now that the release is final I’m actually glad with the result. All the issues I raised from the early draft have been fixed. This is what a simple servlet would have looked like in the early draft:

@Servlet(urlMappings={"/foo","/bar"})publicclassMyServlet{@GETpublicvoidhandleGet(HttpServletRequestreq,HttpServletResponseres){//Handle the GET
}}

And this was my suggestion on how to improve it (see second article/link):

That’s very similair, maybe a little too similair..? But anyway, I’m pleased about the result. It’ll be a lot easier in the future to write Servlets and Filters and a lot of cool new features have been added too.

I love the spec, despite the lack of feedback and replies from the expert group, ignoring all positive feedback and constructive advice. If I now look at the way the annotations turned out its almost identical to my first sketch after their JavaOne presentation in March 2008.